单词搜索
时间复杂度:
(网格的每个点都要去遍历一次,每次最多拓展4*len的点)
const int dx[] = {-1,0,1,0} ;
const int dy[] = {0,1,0,-1} ;
class Solution {
public:
bool vis[210][210] = {0};
int m,n;
bool exist(vector<vector<char>>& board, string word) {
m = board.size();
n = board[0].size();
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(dfs(i,j,0,word,board)){
return true;
}
}
}
return false;
}
bool dfs(int x,int y,int idx,const string&s,vector<vector<char>>& board) {
if(board[x][y] == s[idx]) {
vis[x][y] = 1;
if(idx==s.size()-1) {
return true;
}
for(int k=0;k<4;k++) {
int nx = x + dx[k];
int ny = y + dy[k];
if( nx>=0 && nx<m && ny>=0 && ny<n && !vis[nx][ny]) {
if(dfs(nx,ny,idx+1,s,board)){
return true;
}
}
}
vis[x][y] = 0; //这一层全部搜索完,回溯。
}
return false;
}
};