剑指offer12:矩阵中的路径

题目描述

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 
 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

 思路:回溯法

public class Solution {
    public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
    {
        if(str.length == 0) return false;
        for(int i = 0;i < rows;i++){
            for(int j = 0;j<cols;j++){
                if(matrix[i*cols+j] == str[0]){
                    int[] flagMatrix = new int[rows*cols];
                    boolean flag = hasPath(matrix,cols,str,0,flagMatrix,i,j);
                    if(flag == true)
                        return true;
                }
            }
        }
        return false;
    }
    public static boolean hasPath(char[] matrix, int cols,
                    char[] str,int index,int[] flagMatrix,int i,int j){
        if(index == str.length)
            return true;
        if(i*cols+j>=matrix.length || i*cols+j < 0)
            return false;
        if(str[index] != matrix[i*cols+j] || flagMatrix[i*cols+j]==1)
            return false;
        if(str[index] == matrix[i*cols+j] && flagMatrix[i*cols+j]==0){
            flagMatrix[i*cols+j] = 1;
        }
        return hasPath(matrix,cols,str,index+1,flagMatrix,i-1,j)||
                hasPath(matrix,cols,str,index+1,flagMatrix,i,j+1)||
                hasPath(matrix,cols,str,index+1,flagMatrix,i+1,j)||
                hasPath(matrix,cols,str,index+1,flagMatrix,i,j-1);
    }
}

刚开始的错误解法:

if(judgeBound(i-1,j,cols,matrix.length) && matrix[(i-1)*cols+j] == str[index+1] && flagMatrix[i-1][j] == 0){//上
            return hasPath(matrix,cols,str,index+1,flagMatrix,i-1,j);
        }
        else if(judgeBound(i,j+1,cols,matrix.length) && matrix[i*cols+j+1] == str[index+1] && flagMatrix[i][j+1] == 0){//右
            return hasPath(matrix,cols,str,index+1,flagMatrix,i,j+1);
        }
        else if(judgeBound(i+1,j,cols,matrix.length) && matrix[(i+1)*cols+j] == str[index+1] && flagMatrix[i+1][j] == 0){//下
            return hasPath(matrix,cols,str,index+1,flagMatrix,i+1,j);
        }else if(judgeBound(i,j-1,cols,matrix.length) &&matrix[i*cols+j-1] == str[index+1] && flagMatrix[i][j-1] == 0){//左
            return hasPath(matrix,cols,str,index+1,flagMatrix,i,j-1);
        }else{
            return false;
        }

上边代码错误的原因:我们应当上右下左进行利用或的关系进行判断,只要有一个方向满足即可继续往下走,但是上边的代码只要有一个方向返回true或false就直接跳出递归返回。

原文地址:https://www.cnblogs.com/ttzz/p/13893765.html