79 单词搜索
class Solution {
private:
int rows, cols;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
bool dfs(vector<vector<char>>& board, const string& word, int x, int y,
int idx) {
if (board[x][y] != word[idx])
return false;
if (idx == word.size() - 1)
return true;
for (int i = 0; i < 4; i++) {
int a = x + dx[i];
int b = y + dy[i];
if (a >= 0 && a < rows && b >= 0 && b < cols) {
board[x][y] = '\0';
if (dfs(board, word, a, b, idx + 1))
return true;
board[x][y] = word[idx];
}
}
return false;
}
public:
bool exist(vector<vector<char>>& board, string word) {
rows = board.size();
cols = board[0].size();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (dfs(board, word, i, j, 0))
return true;
}
}
return false;
}
};