递归
class Solution {
public:
int row=0;
int col=0;
int len=0;
bool dfs(vector<vector<char>>& board,vector<vector<bool>>& finded,string &word,int k,int i,int j){
if(k==len-1)return 1;
if(i-1>-1&&finded[i-1][j]==0&&board[i-1][j]==word[k+1]){
finded[i-1][j]=1;
if(dfs(board,finded,word,k+1,i-1,j))return 1;
finded[i-1][j]=0;
}
if(i+1<row&&finded[i+1][j]==0&&board[i+1][j]==word[k+1]){
finded[i+1][j]=1;
if(dfs(board,finded,word,k+1,i+1,j))return 1;
finded[i+1][j]=0;
}
if((j-1>-1)&&(finded[i][j-1]==0)&&(board[i][j-1]==word[k+1])){
finded[i][j-1]=1;
if(dfs(board,finded,word,k+1,i,j-1))return 1;
finded[i][j-1]=0;
}
if(j+1<col&&finded[i][j+1]==0&&board[i][j+1]==word[k+1]){
finded[i][j+1]=1;
if(dfs(board,finded,word,k+1,i,j+1))return 1;
finded[i][j+1]=0;
}
return 0;
}
bool exist(vector<vector<char>>& board, string word) {
row=board.size();
col=board[0].size();
len=word.size();
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(board[i][j]==word[0]){
vector<vector<bool>>finded(row,vector<bool>(col,0));
finded[i][j]=1;
if(dfs(board,finded,word,0,i,j))return 1;
}
}
}
return 0;
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/27e29ff4d86ddd80345d88715bb5239c.png)