Leetcode題目79.單詞搜索(回溯+DFS-中等)

題目描述:java

給定一個二維網格和一個單詞,找出該單詞是否存在於網格中。blog

單詞必須按照字母順序,經過相鄰的單元格內的字母構成,其中「相鄰」單元格是那些水平相鄰或垂直相鄰的單元格。同一個單元格內的字母不容許被重複使用。it

示例:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

給定 word = "ABCCED", 返回 true.
給定 word = "SEE", 返回 true.
給定 word = "ABCB", 返回 false.

代碼實現:io

class Solution {
     public static boolean exist(char[][] board, String word) {

        if (board.length == 0) {
            return false;
        }
        //網格的行數
        int row = board.length;
        //網格的列數
        int col = board[0].length;
        //表示網格是否已經被訪問過的狀態
        boolean[][] visited = new boolean[row][col];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (board[i][j] == word.charAt(0) && backTrace(i, j, 0, board, word, visited)) {
                    return true;
                }
            }
        }
        return false;
    }

    //DFS+回溯
    private static boolean backTrace(int i, int j, int index, char[][] board, String word, boolean[][] visited) {

        if (index == word.length()) {
            return true;
        }
        //二維平面按照上->右->下->左的順序搜索
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(index) || visited[i][j]) {
            return false;
        }
        //標記當前網格已經被訪問
        visited[i][j] = true;
        if (backTrace(i - 1, j, index + 1, board, word, visited)
                || backTrace(i, j + 1, index + 1, board, word, visited)
                || backTrace(i + 1, j, index + 1, board, word, visited)
                || backTrace(i, j - 1, index + 1, board, word, visited)) {

            return true;
        }
        //回溯
        visited[i][j] = false;
        return false;
    }
}
相關文章
相關標籤/搜索