题目描述
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 下面3*4矩阵中包含一条字符串“bfce”的路径(路径中的字母用加粗标出),但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
a b t g
c f c s
j d e h
解题思路
这是一个经典的回溯问题。对于这种路径问题,一般有广度优先和深度优先两种解决方案,比较常用的是深度优先遍历方案。下面分析深度优先解决方案。
首先,在矩阵中任选一个格子作为路径起点。假设矩阵中某个格子的字符为ch,并且这个格子将对应于路径上的第i个位置,假设路径上的第i个字符不是ch,那么这个格子不可能处在路径上的第i个位置。如果路径上的第i个字符正好是ch,那么到相邻的格子上去寻找路径上的第i+1个字符。除矩阵边界上的格子外其他格子都有4个相邻的格子。重复这个过程直到路径上的所有字符都在矩阵上找到位置。
由于回溯法的递归特性,路径可以被看成一个栈。当在矩阵中定位了路径中前n个字符的位置后,在与第n个字符位置周围都无法找到第n+1个字符时,表示当前路径不正确,只需弹出第n个字符回到第n-1个字符的位置即可。同时,因为格子不能重复使用,我们还需要定义一个record数组来记录已被使用的格子。
Java代码
public class Solution {
public boolean hasPath(char[] matrix, int rows, int cols, char[] str) throws Exception
{
if(matrix==null||matrix.length==0||matrix.length<str.length){
return false;
}
if(matrix.length!=rows*cols){
throw new Exception("Invalid data");
}
int[][] record = new int[rows][cols];
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(matrix[i*cols+j] == str[0]){
record[i][j] = 1;
if(dfs(matrix,rows,cols,i,j,str,1,record)){
return true;
}else{
record[i][j] = 0;
}
}
}
}
return false;
}
public boolean dfs(char[] matrix,int rows,int cols,int stepY,int stepX,char[] str,int step,int[][] record){
if(step==str.length){
return true;
}
if(stepY>0&&record[stepY-1][stepX]!=1&&matrix[(stepY-1)*cols+stepX]==str[step]){
step++;
record[--stepY][stepX] = 1;
if(dfs(matrix,rows,cols,stepY,stepX,str,step,record)){
return true;
}else{
step--;
record[stepY++][stepX] = 0;
}
}
if(stepY<rows-1&&record[stepY+1][stepX]!=1&&matrix[(stepY+1)*cols+stepX]==str[step]){
step++;
record[++stepY][stepX] = 1;
if(dfs(matrix,rows,cols,stepY,stepX,str,step,record)){
return true;
}else{
step--;
record[stepY--][stepX] = 0;
}
}
if(stepX<cols-1&&record[stepY][stepX+1]!=1&&matrix[stepY*cols+stepX+1]==str[step]){
step++;
record[stepY][++stepX] = 1;
if(dfs(matrix,rows,cols,stepY,stepX,str,step,record)){
return true;
}else{
step--;
record[stepY][stepX--] = 0;
}
}
if(stepX>0&&record[stepY][stepX-1]!=1&&matrix[stepY*cols+stepX-1]==str[step]){
step++;
record[stepY][--stepX] = 1;
if(dfs(matrix,rows,cols,stepY,stepX,str,step,record)){
return true;
}else{
step--;
record[stepY][stepX++] = 0;
}
}
return false;
}
}