题目描述:设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中任意一格开始,分别向上下左右四个方向都可以移动。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。
解题思路:这是一个回溯法的经典题,最常用就是递归来做。用递归解题的最主要问题就是要注意递归的边界条件。本题为目标字符串遍历完成,即可return。还有一点需要注意,就是题目中提及,矩阵中的每一格只能遍历一次,所以要有一个同样大小的矩阵来判断每一格是否被遍历过。
class Solution {
public:
bool path(char *matrix,int rows,int cols,int row,int col,char *str,int& loc,bool *visited)
{
if(str[loc]=='\0')
{
return true;
}
bool haspath=false;
if(row>=0 && row<rows &&col >=0 &&col<cols &&
matrix[row*cols+col]==str[loc]&& visited[row*cols+col]==false)
{
loc++;
visited[row*cols+col]=true;
haspath=path(matrix,rows,cols,row-1,col,str,loc,visited)||
path(matrix,rows,cols,row+1,col,str,loc,visited)||
path(matrix,rows,cols,row,col-1,str,loc,visited)||
path(matrix,rows,cols,row,col+1,str,loc,visited);
if(!haspath)
{
loc--;
visited[row*cols+col]=false;
}
}
return haspath;
}
bool hasPath(char* matrix, int rows, int cols, char* str)
{
if(matrix==nullptr || rows==0 || cols==0 || str==nullptr)
{
return false;
}
bool res=false;
int loc=0;
bool *visited=new bool[rows*cols];
memset(visited,0,rows*cols);
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
res=path(matrix,rows,cols,i,j,str,loc,visited);
if(res==true)
{
return true;
}
}
}
delete []visited;
return res;
}
};