剑指Offer(Java实现):矩阵中的路径

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

思路
这道题目用到了回溯法,就是从一个字母出发,列出其上下左右所有可能的字母,然后与目标字符串比对,符合就继续比对下一个,不符合就返回去比对其它方位的字母,如此反复。

代码

public class T12 {
    public boolean hasPath(char[] matrix,int rows,int cols,char[] str){
        if(matrix == null || rows < 1 || cols < 1 || str == null)
            return false;

        boolean[] visited = new boolean[rows * cols];
        for(int i = 0;i < rows;i++){
            for(int j = 0;j < cols;j++){
                if(hasPathcore(matrix,rows,cols,i,j,0,str,visited)){
                    return true;
                }
            }
        }
        return false;
    }

    private boolean hasPathcore(char[] matrix, int rows, int cols, int i, int j, int k, char[] str, boolean[] visited) {
    int index = i * cols + j;
    if(i < 0 || i >= rows || j < 0 || j >= cols || matrix[index] != str[k] || visited[index])
        return false;
    visited[index] = true;
    //如果递归最后一个位置的字符,则表明前面位置的字符都在矩阵中找到了对应的位置
        if(k == str.length - 1)
            return true;
        //如果没有递归最后一个位置的字符,则继续递归,k+1表示继续在矩阵中寻找str数组中下一个位置的字符在矩阵中的位置
        if(hasPathcore(matrix,rows,cols,i - 1,j,k+1,str,visited)
                ||hasPathcore(matrix,rows,cols,i + 1,j,k + 1,str,visited)
                ||hasPathcore(matrix, rows, cols, i, j - 1, k + 1, str, visited)
                ||hasPathcore(matrix, rows, cols, i, j+1, k + 1, str, visited)){
            return true;
        }else{
            k--;
            visited[index] = false;
        }
        return false;
    }
    public static void main(String[] args) {
        String s= "abtgcfcsjdeh";
        String s2 = "bfce";
        char[] matrix = s.toCharArray();
        char[] str = s2.toCharArray();
        boolean b = new T12().hasPath(matrix, 3, 4, str);
        System.out.println(b);
    }

}
发布了49 篇原创文章 · 获赞 4 · 访问量 2514

猜你喜欢

转载自blog.csdn.net/weixin_42040292/article/details/104055559
今日推荐