矩阵中的路径
请设计一个哈桑农户,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个各自,则该路径不能再进入该各自。例如[a b c e, s f c s, a d e e]矩阵中包含一条字符串“bcced”的路径,但是矩阵中不包含“abcb”路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个各自之后,路径不能再次进入该格子。
题解:
利用回溯法实现。
class Solution {
public:
bool ishasPath(const char* matrix, int rows, int cols, int i,int j,const char* str,int& len,bool* status){
if(str[len]=='\0')
return true;
bool isPath=false;
if(i>=0&&i<rows && j>=0&&j<cols && matrix[i*cols+j]==str[len] && !status[i*cols+j]){//进行该位置的判断
len++;
status[i*cols+j]=1;
//进行4邻域的判断
isPath=ishasPath(matrix,rows,cols,i-1,j,str,len,status)||
ishasPath(matrix,rows,cols,i,j-1,str,len,status)||
ishasPath(matrix,rows,cols,i+1,j,str,len,status)||
ishasPath(matrix,rows,cols,i,j+1,str,len,status);
if(!isPath){//回溯
len--;
status[i*rows+j]=0;
}
}
return isPath;
}
bool hasPath(char* matrix, int rows, int cols, char* str){
if(matrix==nullptr||rows<1||cols<1||!str) return false;
bool *status=new bool[rows*cols];//生成相同大小的状态矩阵
memset(status,0,rows*cols);
int pathlen=0;
for(int i=0;i<rows;i++){//起始点遍历
for(int j=0;j<cols;j++){
if(ishasPath(matrix,rows,cols,i,j,str,pathlen,status))//对起始点斤西瓜判断
return true;
}
}
delete[] status;
return false;
}
};