题目描述
判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向上下左右移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。
例如下面的矩阵包含了一条 bfce 路径。
解题思路
使用回溯法(backtracking)进行求解,它是一种暴力搜索方法,通过搜索所有可能的结果来求解问题。回溯法在一次搜索结束时需要进行回溯(回退),将这一次搜索过程中设置的状态进行清除,从而开始一次新的搜索过程。例如上图示例中,从 f 开始,下一步有 4 种搜索可能,如果先搜索 b,需要将 b 标记为已经使用,防止重复使用。在这一次搜索结束之后,需要将 b 的已经使用状态清除,并搜索 c。
class Solution {
private:
bool isPath(char *matrix,vector<char> flags,char* str,int x,int y,int rows, int cols)
{
if(x<0 || x>=rows || y<0 || y>=cols) //越界的点
return false;
if( matrix[x*cols+y]== *str && flags[x*cols+y]==0 )
{
flags[x*cols+y]=1;
if(*(str+1)==0) // 字符串结尾了(最后一个满足的)
return true;
bool condition =isPath(matrix,flags,(str+1),x,y-1,rows,cols) ||
isPath(matrix,flags,(str+1),x-1,y,rows,cols)||
isPath(matrix,flags,(str+1),x,y+1,rows,cols)||
isPath(matrix,flags,(str+1),x+1,y,rows,cols);
if(condition == false)
flags[x*cols+y]=0;
return condition;
}
else
return false;
}
public:
bool hasPath(char* matrix, int rows, int cols, char* str)
{
vector<char> flags(rows*cols,0);
bool condition=false;
for(int i=0;i<rows;i++)
for(int j=0;j<cols;j++)
{
condition= (condition || isPath(matrix,flags,str,i,j,rows,cols) );
}
return condition;
}
};