// 递归求解
static int x=[](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if (word.length() <= 0)
return false;
if (board.size() <= 0 || board[0].size() <= 0)
return false;
vector<vector<bool>> visit(board.size(), vector<bool>(board[0].size(), false));
for (int i = 0; i < board.size(); i++)
for (int j = 0; j < board[0].size(); j++){
if (word[0] == board[i][j])
if (solve(i, j, 0, board, word, visit))
return true;
}
return false;
}
bool solve(int row, int col, int index, vector<vector<char>>& board, string& word, vector<vector<bool>>& visit){
if (index == word.length())
return true;
if (row >= board.size() || row < 0 || col >= board[0].size() || col < 0 || visit[row][col] ||word[index] != board[row][col])
return false;
visit[row][col] = true;
// 四个方向尝试
if (solve(row + 1, col, index + 1, board, word, visit) ||
solve(row - 1, col, index + 1, board, word, visit) ||
solve(row, col + 1, index + 1, board, word, visit) ||
solve(row, col - 1, index + 1, board, word, visit))
return true;
// 记得还原标记
visit[row][col] = false;
return false;
}
};
LetCode 79. 单词搜索
最新推荐文章于 2025-05-31 15:27:22 发布