题目:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中任意一格开始,每一步可以在矩阵中间向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。
https://cuijiahua.com/blog/2018/02/basis_65.html
bool hasPathCore(char *str, int rows, int cols, int row, int col, char *target, int *pathLen, bool *visited) {
if (target[*pathLen] == '\0') {
return true;
}
int index = row * cols + col;
bool hasPath = false;
if(row < rows && col < cols && str[index] == target[*pathLen] && !visited[index]) {
pathLen++;
visited[index] = true;
hasPath = hasPathCore(str,rows,cols,row,col-1,target,pathLen, visited) ||
hasPathCore(str,rows,cols,row-1,col,target,pathLen, visited) ||
hasPathCore(str,rows,cols,row,col+1,target,pathLen, visited) ||
hasPathCore(str,rows,cols,row+1,col,target,pathLen, visited);
if(!hasPath) {
pathLen--;
visited[index] = false;
}
}
return hasPath;
}
bool findPath(char *str, int rows, int cols, char *target) {
if (NULL == str || (0 == rows && cols == 0) || NULL == target) {
return false;
}
int pathLen = 0;
bool *visited = (bool*)malloc(sizeof(bool)*rows*cols);
memset(visited, 0, rows*cols);
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
bool hasPath;
hasPath = hasPathCore(str, rows, cols, row, col, target, &pathLen,visited);
if (hasPath) {
free(visited);
return true;
}
}
}
free(visited);
return false;
}