美文网首页
面试题12:矩阵中的路径

面试题12:矩阵中的路径

作者: scott_alpha | 来源:发表于2019-10-05 22:24 被阅读0次

    题目:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。例如,在下面的3*4的矩阵中包含一条字符串“bfce”的路径。但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子后,路径不能再次进入这个格子。
    a b t g
    c f c s
    j d e h
    思路:使用回溯法,定位到当前字符,然后在字符的四周找下一个字符,如果找到则继续,如果没有找到则回退到上一个字符,一直重复这个过程。
    解决方案:

    public class Question12 {
        public static boolean hasPath(char[] matrix, int rows, int cols, char[] str){
            if (matrix == null || rows < 1 || cols < 1 || str == null){
                return false;
            }
    
            boolean[] isVisited = new boolean[rows * cols];
    
            int pathLength = 0;
            for (int row=0; row < rows; row++){
                for (int col=0; col < cols; col++){
                    if (hasPathCore(matrix, rows, cols, row, col, str, pathLength, isVisited)){
                        return true;
                    }
                }
            }
            return false;
        }
        private static boolean hasPathCore(char[] matrix, int rows, int cols, int row, int col, char[] str, int pathLength, boolean[] isVisited){
            if (pathLength == str.length) return true;
            boolean hasPath = false;
            if (row >= 0 && row < rows && col >= 0 &&col < cols && matrix[row * cols + col] == str[pathLength] && !isVisited[row * cols + col]){
                ++pathLength;
                isVisited[row * cols + col] = true;
                hasPath = hasPathCore(matrix, rows, cols, row, col - 1, str, pathLength, isVisited)
                        || hasPathCore(matrix, rows, cols, row - 1, col, str, pathLength, isVisited)
                        || hasPathCore(matrix, rows, cols, row, col + 1, str, pathLength, isVisited)
                        || hasPathCore(matrix, rows, cols, row + 1, col, str, pathLength, isVisited);
                if (!hasPath){
                    --pathLength;
                    isVisited[row * cols + col] = false;
                }
            }
            return hasPath;
        }
    
        public static void main(String[] args) {
            char[] matrix = "ABTGCFCSJDEH".toCharArray();
            int rows = 3;
            int cols = 4;
    //        char[] str = "BFCE".toCharArray();
            char[] str = "ABFB".toCharArray();
            System.out.println(hasPath(matrix, rows, cols, str));
        }
    }
    

    相关文章

      网友评论

          本文标题:面试题12:矩阵中的路径

          本文链接:https://www.haomeiwen.com/subject/ovqypctx.html