题目描述
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
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>>& matrix, string str){
int rows = matrix.size();
if(rows == 0)
return false;
int cols = matrix[0].size();
if(cols == 0)
return false;
int strLength = str.length();
if(strLength == 0)
return false;
bool visited[rows * cols]; // 这里用二维数组更方便,但是最好用vector<vector<bool> >,传它的引用
memset(visited, 0, sizeof(visited)); // memset只能初始化0/-1
int strPosition = 0;
for(int i=0; i < rows; i++){
for(int j=0; j < cols; j++){
if(hashPathRecusively(matrix, rows, cols, i, j, str, strPosition, visited)){
return true;
}
}
}
return false;
}
// 扯淡一般的结果,在这个函数形参列表里,之前没加引用,报超时错误。
bool hashPathRecusively(vector<vector<char>> &matrix, int rows, int cols, int row, int col,
string &str, int strPosition, bool* visited){
if(strPosition == str.length())
return true;
bool hasPath = false; // 默认值(重要!)
if(row >= 0 && row < rows && col >= 0 && col < cols &&
matrix[row][col] == str[strPosition] && !visited[row*cols + col]){
strPosition++;
visited[row*cols + col] = true;
hasPath = hashPathRecusively(matrix, rows, cols, row-1, col, str, strPosition, visited) ||
hashPathRecusively(matrix, rows, cols, row+1, col, str, strPosition, visited) ||
hashPathRecusively(matrix, rows, cols, row, col-1, str, strPosition, visited) ||
hashPathRecusively(matrix, rows, cols, row, col+1, str, strPosition, visited);
if(!hasPath){ // 这里回溯时不加这个if也可以! 只是《剑指offer》上是这么写的
strPosition--;
visited[row*cols + col] = false;
}
}
return hasPath;
}
};
有个很坑爹的超时错误,在这个函数形参列表里,之前没加引用,报超时错误。
本文介绍了一个经典的回溯问题,即在二维网格中查找指定单词的算法实现。文章详细解释了如何通过递归方式检查单词路径,确保单词按顺序且不重复使用同一单元格内的字母。
970

被折叠的 条评论
为什么被折叠?



