class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if(board.size()<=0) return false;
int m = board.size()-1;
int n = board[0].size()-1;
vector<vector<bool>> visited(m+1,vector<bool>(n+1,false));
for(int i=0;i<=m;i++){
for(int j=0;j<=n;j++){//从i和j每一个位置出发,
if(has_exist(board,word,i,j,visited)) return true;
}
}
return false;
}
bool has_exist(vector<vector<char>>& board, string word,int i,int j,vector<vector<bool>> & visited){
if(word.length()==1){
if(!visited[i][j] && board[i][j]==word[0]) return true;
else return false;
}
int m = board.size()-1;
int n = board[0].size()-1;
if(board[i][j]==word[0] && !visited[i][j]){//第一个匹配上了
visited[i][j]=true;
if(i>=1 && has_exist(board,word.substr(1,word.length()-1),i-1,j,visited)) return true;
if (i<m && has_exist(board,word.substr(1,word.length()-1),i+1,j,visited)) return true;
if (j>=1 && has_exist(board,word.substr(1,word.length()-1),i,j-1,visited)) return true;
if (j<n && has_exist(board,word.substr(1,word.length()-1),i,j+1,visited)) return true;
visited[i][j]=false;
}
return false;
}
};