题目描述
假设矩阵为 matrix,字符串为 str,定义一个与矩阵等大小的 bool 矩阵 isVisited 用于标记格子是否被访问。
1. 当在矩阵 matrix 中找到一个匹配字符串 str 的 index 处字符的格子,标记此格子为已访问。
2. 从该格子开始沿四个方向递归查找下一个格子匹配 str 的 index 处的下一个字符。
1) 若找到,则继续递归匹配下一个字符,以此递归直到匹配到 str 的末尾,或者匹配不到了。
2) 若找不到,则回溯,重新选择下一个和 index 处匹配的格子。
bool hasPath(char* matrix, int rows, int cols, char* str, int r, int c, int& index, bool* isVisited) {
if('\0' == str[index])// 如果到了字符串 str 的末尾, 则表示矩阵中存在一个路径
return true;
bool isHasPath = false;
// 如果座标 <r, c> 处的格子匹配字符串 str 的 index 处的字符,则朝四个方向递归查找下一个匹配的字符
if(r >= 0 && r < rows && c >= 0 && c < cols &&
matrix[r*cols+c] == str[index] && !isVisited[r*cols+c]) {
index++;
isVisited[r*cols+c] = true;// 标记座标 <r, c> 处的格子为已访问
isHasPath = hasPath(matrix, rows, cols, str, r, c+1, index, isVisited) ||// 朝右找
hasPath(matrix, rows, cols, str, r+1, c, index, isVisited) ||// 朝下找
hasPath(matrix, rows, cols, str, r, c-1, index, isVisited) ||// 朝左找
hasPath(matrix, rows, cols, str, r-1, c, index, isVisited);// 朝上找
if(!isHasPath) {// 如果无法找到下一个匹配的格子,则回溯,重新选择和当前字符匹配的格子
index--;
isVisited[r*cols+c] = false;
}
}
return isHasPath;
}
bool HasPath(char* matrix, int rows, int cols, char* str) {// 【矩阵中的路径(回溯法解决)】
if(NULL == matrix || NULL == str || cols <= 0 || cols <= 0)
return false;
bool *isVisited = new bool[rows * cols]();// 用来标记格子是否被访问过,初始化全为 0,即 false
int index = 0;
for(int r=0; r < rows; r++)
for(int c=0; c < cols; c++)
if(hasPath(matrix, rows, cols, str, r, c, index, isVisited)) {
delete[] isVisited;
return true;
}
delete[] isVisited;
return false;
}