请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。
例如下面矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
思路:回溯法,循环从每一个起点出发,依次遍历上下左右,同时记录当前字符串比较下标,做为回溯的出口。
回溯的思路是失败的尝试后,回撤之前设置的值。
bool hasPath(char* matrix, int rows, int cols, char* str)
{
if (NULL == matrix || cols <=0 || rows <=0 || NULL == str)
{
return false;
}
bool visited[rows*cols];
memset(&visited, false, rows*cols); // 务必初始化在栈的数组
int k =0;
for (int i=0; i<rows; i++)
{
for (int j=0; j<cols; j++)
{
if (isPath(matrix, rows, cols, i, j, k, str, visited))
{
return true;
}
}
}
return false;
}
bool isPath(char* matrix, int rows, int cols, int i, int j, int k, char* str, bool *visited)
{
if (strlen(str) == k)
{
return true;
}
if ( i < 0 || i >= rows || j<0 || j >= cols || visited[i*cols +j])
{
return false;
}
if (matrix[i*cols + j] == str[k])
{
visited[i*cols + j] = true;
if (isPath(matrix, rows, cols, i+1, j, k+1, str, visited)
|| isPath(matrix, rows, cols, i-1, j, k+1, str, visited)
|| isPath(matrix, rows, cols, i, j+1, k+1, str, visited)
|| isPath(matrix, rows, cols, i, j-1, k+1, str, visited)
)
{
return true;
}
visited[i*cols + j] = false;
}
return false;
}
[点击并拖拽以移动]