给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
给定 word = "ABCCED", 返回 true
给定 word = "SEE", 返回 true
给定 word = "ABCB", 返回 false
对表格中每个字母都进行回溯搜索,代码都有解释
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
rows = board.size(), columns = board[0].size();//获得行列的尺寸
for(int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (backtrack(board, word, i, j, 0)) return true; // 每个格子都进行回溯判断
}
}
return false;
}
private:
int rows, columns;
bool backtrack(vector<vector<char>>& board, string& word, int x, int y, int index) {
// 结束条件
// 越界或者当前字母位不相等
if (x >= rows || x < 0 || y >= columns || y < 0 || board[x][y] != word[index]) {
return false;
}
// 最后一个字母也相等,返回成功
if (index == word.size() - 1){
return true;
}
// 避免重复使用
board[x][y] = ' '; //到达board[x][y] = ' ';的时候,表明已经满足条件board[x][y] == word[index]
//因此,将board[x][y]旁边的点与 word[index+1]对比,所以避免重复使用将board[x][y]置空
// 回溯
if (backtrack(board, word, x - 1, y, index + 1)
|| backtrack(board, word, x + 1, y, index + 1)
|| backtrack(board, word, x, y - 1, index + 1)
|| backtrack(board, word, x, y + 1, index + 1))
{
return true;
}
// 如果不通,回溯至上一个状态
board[x][y] = word[index];
return false;
}
};
作者:wei-ming-26
链接:https://leetcode-cn.com/problems/word-search/solution/79-dan-ci-sou-suo-hui-su-dai-ma-jian-ji-y7rfq/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。