题目描述
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子
思路:回溯法
class Solution {
public:
bool isOk(
char *matrix,
int rows,
int cols,
char *str,
bool *pVisited,
int i,
int j,
int k)
{
if(i>rows-
1 || i<
0)
return false;
if(j>cols-
1 || j<
0)
return false;
if(matrix[i*cols+j]!=str[k])
return false;
if(pVisited[i*cols+j]==
true)
return false;
return true;
}
void findPath(
char *matrix,
int rows,
int cols,
char *str,
int i,
int j,
int k,
bool &res,
bool *
pVisited)
{
if(res==
true)
return;
if(str[k]==
'\0')
{
res=
true;
return;
}
if(isOk(matrix, rows, cols, str, pVisited, i+
1, j, k))
{
pVisited[(i+
1)*cols+j]=
true;
findPath(matrix, rows, cols, str, i+
1, j, k+
1, res, pVisited);
pVisited[(i+
1)*cols+j]=
false;
}
if(isOk(matrix, rows, cols, str, pVisited, i, j+
1, k))
{
pVisited[i*cols+j+
1]=
true;
findPath(matrix, rows, cols, str, i, j+
1, k+
1, res, pVisited);
pVisited[i*cols+j+
1]=
false;
}
if(isOk(matrix, rows, cols, str, pVisited, i-
1, j, k))
{
pVisited[(i-
1)*cols+j]=
true;
findPath(matrix, rows, cols, str, i-
1, j, k+
1, res, pVisited);
pVisited[(i-
1)*cols+j]=
false;
}
if(isOk(matrix, rows, cols, str, pVisited, i, j-
1, k))
{
pVisited[i*cols+j-
1]=
true;
findPath(matrix, rows, cols, str, i, j-
1, k+
1, res, pVisited);
pVisited[i*cols+j-
1]=
false;
}
}
bool hasPath(
char* matrix,
int rows,
int cols,
char*
str)
{
bool res=
false;
if(matrix==NULL || rows==
0 || cols==
0 || str==NULL)
return res;
bool *pVisited=
new bool[rows*
cols];//记录某个点是否被访问过
for(
int idx=
0; idx<rows*cols; ++idx)*(pVisited+idx)=
false;
for(
int i=
0; i<rows; ++
i)
{
for(
int j=
0; j<cols; ++
j)
{
if(matrix[i*cols+j]==str[
0])//找到起点
{
pVisited[i*cols+j]=
true;
findPath(matrix, rows, cols, str, i, j, 1, res, pVisited);
pVisited[i*cols+j]=
false;
}
}
}
return res;
}
};
转载于:https://www.cnblogs.com/jeysin/p/8079496.html
相关资源:JAVA上百实例源码以及开源项目