1.题目
2.解法
回溯+dfs(深度优先搜索)
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int m = board.size(), n = board[0].size();
vector<vector<bool>> used(m, vector<bool>(n, false));
bool t = false;
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
if (board[i][j] == word[0]) {
used[i][j] = true;
if(t || dfs(board, word, used, i, j, 1)) return true;
used[i][j] = false;
}
}
}
return false;
}
bool dfs(vector<vector<char>>& board, string word, vector<vector<bool>>& used, int ri, int cj, int index) {
if (index == word.length()) return true;
if (ri-1 >= 0 && used[ri-1][cj] == false && board[ri-1][cj] == word[index]) {
used[ri-1][cj] = true;
if (dfs(board, word, used, ri-1, cj, index+1)) return true;
used[ri-1][cj] = false;
}
if (ri+1 < board.size() && used[ri+1][cj] == false && board[ri+1][cj] == word[index]) {
used[ri+1][cj] = true;
if (dfs(board, word, used, ri+1, cj, index+1)) return true;
used[ri+1][cj] = false;
}
if (cj-1 >= 0 && used[ri][cj-1] == false && board[ri][cj-1] == word[index]) {
used[ri][cj-1] = true;
if (dfs(board, word, used, ri, cj-1, index+1)) return true;
used[ri][cj-1] = false;
}
if (cj+1 < board[0].size() && used[ri][cj+1] == false && board[ri][cj+1] == word[index]) {
used[ri][cj+1] = true;
if (dfs(board, word, used, ri, cj+1, index+1)) return true;
used[ri][cj+1] = false;
}
return false;
}
};