class Solution {
public:
bool flag=false;
bool exist(vector<vector<char>>& board, string word) {
char first=word[0];
int row=board.size(),col=board[0].size();
for(int i=0;i<row;++i){
for(int j=0;j<col;++j){
if(board[i][j]==first){
dfs(board,word,i,j,0);
if(flag==true) return true;
}
}
}
return flag;
}
void dfs(vector<vector<char>>& board,string word,int x,int y,int n){
if(n==word.size()){
flag=true;
return;
}
if(x>=board.size()||y>=board[0].size()||x<0||y<0||n>word.size()||board[x][y]!=word[n]) return;
if(board[x][y]==word[n]){
board[x][y]='.';
dfs(board,word,x+1,y,n+1);
dfs(board,word,x,y+1,n+1);
dfs(board,word,x-1,y,n+1);
dfs(board,word,x,y-1,n+1);
board[x][y]=word[n];
}
}
};
标答
class Solution {
public:
bool check(vector<vector<char>>& board, vector<vector<int>>& visited, int i, int j, string& s, int k) {
if (board[i][j] != s[k]) {
return false;
} else if (k == s.length() - 1) {
return true;
}
visited[i][j] = true;
vector<pair<int, int>> directions{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
bool result = false;
for (const auto& dir: directions) {
int newi = i + dir.first, newj = j + dir.second;
if (newi >= 0 && newi < board.size() && newj >= 0 && newj < board[0].size()) {
if (!visited[newi][newj]) {
bool flag = check(board, visited, newi, newj, s, k + 1);
if (flag) {
result = true;
break;
}
}
}
}
visited[i][j] = false;
return result;
}
bool exist(vector<vector<char>>& board, string word) {
int h = board.size(), w = board[0].size();
vector<vector<int>> visited(h, vector<int>(w));
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
bool flag = check(board, visited, i, j, word, 0);
if (flag) {
return true;
}
}
}
return false;
}
};