12-矩阵中的路径-回溯

2020-05-05  本文已影响0人  一方乌鸦

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。例如,在下面的3×4的矩阵中包含一条字符串“bfce”的路径(路径中的字母用加粗标出)。

[["a","b","c","e"],
["s","f","c","s"],
["a","d","e","e"]]

但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。
示例 :
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true

class Solution {
    char[][] board;
    String word;
    boolean[] visited;
    int rows;
    int cols;
    
    public boolean exist(char[][] board, String word) {
        if (word == null || word.length() == 0) return false;
        this.rows = board.length;
        this.cols = board[0].length;
        this.board = board;
        this.word = word;
        this.visited = new boolean[rows * cols];
        
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                if (exist(row, col, 0)) return true;
            }
        }
        return false;
    }

    private boolean exist(int row, int col, int index) {
        if (index == word.length()) return true;
        if (row < 0 || col < 0 || row >= rows || col == cols || visited[row * cols + col]) return false;
        boolean hasPath = false;
        if (board[row][col] == word.charAt(index)) {
            visited[row * cols + col] = true;
            index++;
            hasPath = exist(row - 1, col, index)
            || exist(row + 1, col, index)
            || exist(row, col + 1, index)
            || exist(row, col - 1, index);
            // 重点,如果路径不通,要重置
            if (!hasPath) visited[row * cols + col] = false;
        }
        return hasPath;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读