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 =
[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ]word =
"ABCCED"
, -> returns
true
,
word =
"SEE"
, -> returns
true
,
word =
"ABCB"
, -> returns
false
.
class Solution {
public:bool exist(vector<vector<char>>& board, string word) {
//int m=board.size();
//int n=board[0].size();报错,原因,由于private的isOk()方法已经定义了m n,从新定义就会使m n与原来的m n不一样
m=board.size();
n=board[0].size();
for(int x=0;x<m;x++){
for(int y=0;y<n;y++){
if(isOk(board,word.c_str(),x,y))
return true;
}
}
return false;
}
private:
int m;
int n;
bool isOk(vector<vector<char>>& board,const char* c,int x,int y){
if(x<0||y<0||x>=m||y>=n||board[x][y]=='\0'||board[x][y]!=*c)
return false;
if(*(c+1)=='\0')
return true;
char cc=board[x][y];
board[x][y]='\0';
if(isOk(board,c+1,x+1,y)||isOk(board,c+1,x,y+1)||isOk(board,c+1,x-1,y)||isOk(board,c+1,x,y-1))
return true;
board[x][y]=cc;
return false;
}
};