矩阵中的路径

题目描述:

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

例如,在下面的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 static void main(String[] args) {
        Solution solution = new Solution();
        char[][] board = {{'C','A','A'},{'A','A','A'},{'B','C','D'}};
        System.out.println(solution.exist(board,"AAB"));
    }


    public boolean exist(char[][] board, String word) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                char c = board[i][j];
                if (c == word.charAt(0)){
                    boolean[][] visited = new boolean[board.length][board[0].length];
                    boolean  out = search(board,visited,word,0,i,j);
                    if (out){
                        return true;
                    }
                }
            }
        }
        boolean[][] visited = new boolean[board.length][board[0].length];
        boolean  out = search(board,visited,word,0,1,1);
        return false;
    }

    private boolean search(char[][] board, boolean[][] visited, String string, int index, int i, int j) {
        if (string.length() - 1== index){
            return true;
        }
        visited[i][j] = true;
        char c = string.charAt(index+1);
        int upi = i - 1>=0?(i-1):i;
        int dni = i + 1<board.length?(i + 1):i;
        int ltj = j - 1>=0?(j-1):j;
        int rtj = j + 1<board[0].length?(j + 1):j;

        if (!visited[upi][j] && board[upi][j] == c){
            boolean out = search(board, visited, string, index+1, upi, j);
            if (out) return true;
        }
        if (!visited[dni][j] && board[dni][j] == c){
            boolean out =  search(board, visited, string, index+1, dni, j);
            if (out) return true;
        }
        if (!visited[i][ltj] && board[i][ltj] == c){
            boolean out = search(board, visited, string, index+1, i, ltj);
            if (out) return true;
        }
        if (!visited[i][rtj] && board[i][rtj] == c){
            boolean out = search(board, visited, string, index+1, i, rtj);
            if (out) return true;
        }
        visited[i][j] = false;
        return false;
    }
}

 

上一篇:LeetCode 399. 除法求值


下一篇:[LeetCode题解]79. 单词搜索