class Solution {
public:
int r, c;
bool dfs(int i, int j, int k, vector<vector<char>>& board, string word){
if(i < 0 || i >= r || j < 0 || j >= c || board[i][j] != word[k]){
return false;
}
if(k == word.size() - 1){
return true;
}
board[i][j] = '0'; //防止往回走
bool res = dfs(i + 1, j, k + 1, board, word) ||
dfs(i - 1, j, k + 1, board, word) ||
dfs(i, j + 1, k + 1, board, word) ||
dfs(i, j - 1, k + 1, board, word);
board[i][j] = word[k]; //回溯
return res;
}
bool exist(vector<vector<char>>& board, string word) {
r = board.size();
c = board[0].size();
for(int i = 0; i < r; ++i){
for(int j = 0; j < c; ++j){
if(dfs(i, j, 0, board, word)){
return true;
}
}
}
return false;
}
};
LeetCode 79. 单词搜索
最新推荐文章于 2024-09-06 10:38:06 发布