Description
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example
Given board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false
思路
- 常规的回溯,使用一个标识数组判断是否已经查找过,记得在失败后,把标识重置回去
代码
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int m = board.size();
if(m == 0 || word.size() == 0) return false;
int n = board[0].size();
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
if(board[i][j] == word[0]){
vector<vector<bool>> flag(m, vector<bool>(n, false));
if(judge(board, i, j, m, n, word, 0, flag))
return true;
}
}
}
return false;
}
bool judge(vector<vector<char>>& board, int i, int j, int m, int n,
string& word, int k, vector<vector<bool>>& flag){
if(i < 0 || j < 0 || i == m || j == n
|| flag[i][j] || board[i][j] != word[k])
return false;
flag[i][j] = true;
if(k == word.size() - 1) return true;
bool res = judge(board, i + 1, j, m, n, word, k + 1, flag)
|| judge(board, i - 1, j, m, n, word, k + 1, flag)
|| judge(board, i, j + 1, m, n, word, k + 1, flag)
|| judge(board, i, j - 1, m, n, word, k + 1, flag);
flag[i][j] = false;
return res;
}
};