剑指Offer 12.矩阵中的路径

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

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

但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。

 

示例 1:

输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true

 

思路:当字符第一个相等的时候,开始遍历判断,用一个额外的辅助二维数组,来记录走过的路径。

class Solution {
    public boolean exist(char[][] board, String word) {
        if(board.length == 0 || board[0].length == 0 || word.length() == 0) return false; 
        int[][] visited = new int[board.length][board[0].length]; // 记录是否已经路过,防止一个字符被走2次
        for(int i = 0; i < board.length; i++){
            for(int j = 0; j < board[0].length; j++){
                if(board[i][j] == word.charAt(0)){
                    if(this.existDFS(board, word, visited, i, j, 0)) return true;
                }
            }
        }
        return false;
    }

    public boolean existDFS(char[][] board, String word, int[][] visited, int i, int j, int len){
        if(len == word.length()) return true;
        if(i < 0 || i >= board.length || j < 0 || j >= board[0].length || visited[i][j] == -1 || board[i][j] != word.charAt(len)) return false;
        visited[i][j] = -1; // 标志已经访问过了
        boolean res = this.existDFS(board,word,visited,i, j-1, len+1) || this.existDFS(board,word,visited,i,j+1,len+1) || this.existDFS(board,word,visited,i-1,j,len+1) || this.existDFS(board,word,visited,i+1,j,len+1); // 剪枝,短路或很重要
        visited[i][j] = 0; // 还原,为了下一次继续使用的时候,还是最初始的模样
        return res;
    }
}

 

posted @ 2020-09-10 21:26  星海寻梦233  阅读(193)  评论(0编辑  收藏  举报