请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。例如,在下面的3×4的矩阵中包含一条字符串“bfce”的路径(路径中的字母用加粗标出)。
但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。
示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]],
word = "ABCCED"
输出:true
示例 2:
输入:board = [["a","b"],["c","d"]], word = "abcd"
输出:false
提示:
1 <= board.length <= 200
1 <= board[i].length <= 200
注意:本题与主站 79 题相同:https://leetcode-cn.com/problems/word-search/
对表格中每个字母都进行回溯搜索,代码都有解释
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;
}
// 最后一个字母也相等,返回成功(隐藏包含了board[x][y] == word[index])
if (index == word.size() - 1){
return true;
}
// 避免重复使用
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;
}
};