防止重复查找用finded矩阵记录是否查找过
class Solution {
public:
int row=0;
int col=0;
int n_word=0;
bool check(vector<vector<char>>& board,vector<vector<bool>>& finded,string &word,int i,int j,int k){
// cout<
if(board[i][j]!=word[k]||finded[i][j]==1){
return 0;
}
finded[i][j]=1;
if(k==n_word-1){
return 1;
}
k++;
bool a[4]={0,0,0,0};
if(i-1>=0&&!finded[i-1][j]){
// finded[i-1][j]=1;
a[0]=check(board,finded,word,i-1,j,k);
if(!a[0])finded[i-1][j]=0;
}
if(i+1<row&&!finded[i+1][j]){
// finded[i+1][j]=1;
a[1]=check(board,finded,word,i+1,j,k);
if(!a[1])finded[i+1][j]=0;
}
if(j-1>=0&&!finded[i][j-1]){
// finded[i][j-1]=1;
a[2]=check(board,finded,word,i,j-1,k);
if(!a[2])finded[i][j-1]=0;
}
if(j+1<col&&!finded[i][j+1]){
// finded[i][j+1]=1;
a[3]=check(board,finded,word,i,j+1,k);
if(!a[3])finded[i][j+1]=0;
}
bool b=(a[0]||a[1]||a[2]||a[3])?1:0;
// cout<
return b;
}
bool exist(vector<vector<char>>& board, string word) {
row=board.size();
col=board[0].size();
if(word.empty())return 1;
n_word=word.size();
if(row*col<n_word)return 0;
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));
// cout<<"大循环"<
if(check(board,finded,word,i,j,0))return 1;
}
}
}
return 0;
}
};
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)