题目描述
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
代码
class Solution {
public:
bool hasPath(char* matrix, int rows, int cols, char* str) {
int col = 0;
int row = 0;
int *visited = new int[rows*cols];
//这里必须得用memset赋值 不能用for循环
memset(visited, 1, rows * cols);
int pathLength = 0;
//每一个位置都有可能是起始点 所有每个位置都要遍历一次
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
//这里肯定得加个if判断 不然第一次返回结果为flase则直接返回的就是flase 就不能遍历到以其他点为起点的位置了 这肯定不对
if (hasDiredctPos(matrix, i, j, visited, rows, cols, str, pathLength)) {
return true;
}
}
}
delete[] visited;
return false;
}
bool hasDiredctPos(char * matrix, int row, int col, int * visited, int rows, int cols, char * str, int &pathLength) {
bool hasPath = false;
//如何判断一个char类型数组的长度越界? 用判断该位置元素是否等于 \0 来判断
if (str[pathLength] == '\0') {
return true;
}
//不能直接判断 matrix[row][col] 这个元素是否存在 如果真的不存在会报错的 程序不能继续执行下去
//所以巧妙的用了当前位置的row col 与最大的row col 和最小的row col 相比较的做法
//还得判断该位置是否可以用 并且该位置所在元素是否为str数组对应的顺序位置上所在的元素
if (row >= 0 && row < rows && col >= 0 && col < cols && visited[row*cols+col] && matrix[row*cols+col] == str[pathLength]) {
pathLength++;
visited[row * cols + col] = 0;
hasPath = hasDiredctPos(matrix, row+1, col, visited, rows, cols, str, pathLength) || hasDiredctPos(matrix, row, col+1, visited, rows, cols, str, pathLength) || hasDiredctPos(matrix, row-1, col, visited, rows, cols, str, pathLength) || hasDiredctPos(matrix, row, col-1, visited, rows, cols, str, pathLength);
if (!hasPath) {
pathLength--;
//row * cols + col 是现在该visited二维数组转变为一维后的位置
visited[row * cols + col] = 1;
}
}
return hasPath;
}
};
网友评论