设计一个函数,用来判断在一个矩阵中是否存在一条包含某个字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。
利用回溯法的思想,除矩阵边界上的格子外,其它格子都有四个相邻的格子,当矩阵中坐标为(row,col)的格子和路径字符串下标为pathLength的字符一样时,从四个相邻的格子(row,col-1),(row-1,col),(row+1,col),(row,col+1)中去定位路径字符串中下标为pathLength+1的字符。如果四个相邻的格子都没有匹配到下标为pathLength+1的字符,然后退回到pathLength-1的字符重新定位,递归重复这个过程,直到路径上所有的字符都找到在矩阵中的位置,即str[pathLength] == ‘\0’。
代码如下:
#include<stdio.h>
#include<stdlib.h>
int hasPath2(const char* matrix, int rows, int cols, int row,
int col, const char* str, int pathLength, int *visit)
{
if (str[pathLength] == '\0')
return 1;
int hasPath = 0;
if (row >= 0 && row < rows && col >= 0 && col < cols
&& matrix[row * cols + col] == str[pathLength]
&& !visit[row * cols + col])
{
++pathLength;
visit[row * cols + col] = 1;
//在相邻四个格子中定位
hasPath = hasPath2(matrix, rows, cols, row, col - 1,
str, pathLength, visit)
|| hasPath2(matrix, rows, cols, row - 1, col,
str, pathLength, visit)
|| hasPath2(matrix, rows, cols, row, col + 1,
str, pathLength, visit)
|| hasPath2(matrix, rows, cols, row + 1, col,
str, pathLength, visit);
if (!hasPath)
{
--pathLength;
visit[row * cols + col] = 0;
}
}
return hasPath;
}
int hasPath(const char *matrix, int rows, int cols, const char *str)
{
if (matrix == NULL || rows < 1 || cols < 1 || str == NULL)
return 0;
//存储矩阵数组
int *visit = (int*)malloc(rows*cols*sizeof(int));
//字符串中的路径
int pathLength = 0;
int row, col;
for (row = 0; row < rows; ++row)
{
for (col = 0; col < cols; ++col)
{
if (hasPathCore(matrix, rows, cols, row, col, str, pathLength, visit));
return 1;
}
}
free(visit);
return 0;
}