[leetcode] Word Search

来源:互联网 发布:南京财经大学知乎精华 编辑:程序博客网 时间:2024/04/20 16:55

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example,
Given board =

[  ["ABCE"],  ["SFCS"],  ["ADEE"]]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

这道题目用的是DFS的思想


class Solution {    struct pos{int i;int j;pos(int _i , int _j):i(_i),j(_j){}};private:int m;int n;public:bool exist(vector<vector<char> > &board, string word) {// Start typing your C/C++ solution below// DO NOT write int main() functionm=board.size();n=board[0].size();vector<bool> flagt(n,false);bool (*flag)[100]=new bool[m][100];memset(flag,0,sizeof(bool)*m*100);int length=word.size();int wordp;for(int i=0 ; i<m ; i++){for(int j=0 ; j<n ; j++){wordp=0;if(board[i][j]==word[0] && DFS(board,pos(i,j),flag,word,wordp))return true;memset(flag,0,sizeof(bool)*m*100);}}return false;}bool DFS(vector<vector<char> > &board, pos cur, bool flag[][100], string &word,int p){if(p==word.size())return true;int i,j;i=cur.i,j=cur.j;if(i<0 || j<0 || i>=m || j>=n)return false;if(flag[i][j]==true)return false;flag[i][j]=true;if(board[i][j]!=word[p]){            flag[i][j]=false;return false;}if(DFS(board,pos(i+1,j),flag,word,p+1))return true;if(DFS(board,pos(i,j-1),flag,word,p+1))return true;if(DFS(board,pos(i-1,j),flag,word,p+1))return true;if(DFS(board,pos(i,j+1),flag,word,p+1))return true;return false;}};


	
				
		
原创粉丝点击