
class Solution {
private:
vector<vector<bool>> visit;
int m,n;
int dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}};
bool inarea(int x,int y){
return x>=0 && y>=0 && x<m && y<n;
}
bool search(vector<vector<char>>& board, string word, int index, int startx, int starty){
if(index==(word.size()-1))
return board[startx][starty] == word[index];
if(board[startx][starty] == word[index]){
visit[startx][starty] = true;
for(int i=0;i<4;++i){
int newx = startx + dir[i][0];
int newy = starty + dir[i][1];
if(inarea(newx,newy) && !visit[newx][newy]){
if(search(board,word,index+1,newx,newy)){
return true;
}
}
}
visit[startx][starty] = false;
}
return false;
}
public:
bool exist(vector<vector<char>>& board, string word) {
m=board.size();
assert(m>0);
n=board[0].size();
for(int i=0;i<m;++i){
visit.push_back(vector<bool>(n,false));
}
for(int i=0;i<m;++i){
for(int j=0;j<n;++j){
if(search(board,word,0,i,j)){
return true;
}
}
}
return false;
}
};