[LeetCode] 79. 单词搜索(DFS,回溯)

题目

给定一个二维网格和一个单词,找出该单词是否存在于网格中。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

示例:

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-search
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

DFS+回溯

相关

  • 把回溯理解成递归+剪枝,又DFS使用递归,故DFS+回溯的使用是可行的思路。
  • 关于DFS
    • 判断可否进入都在进入前判断。使逻辑清晰,并减少一层访问。
    • 置已访问及后面再置回都在进入后操作。避免写两次。
    • 事实上,这两个逻辑在里外写都可以(除了可否进入的越界逻辑必须要写在进入前)。

代码

class Solution {
    public static boolean exist(char[][] board, String word) {
        if (board == null || board.length == 0) {
            return false;
        }

        boolean[][] visited = new boolean[board.length][board[0].length];// 默认初始化为false,表示未访问过,可走;true表示已访问,不可走。

        for (int i = 0; i < board.length; ++i) {
            for (int j = 0; j < board[0].length; ++j) {
                if (board[i][j] == word.charAt(0)) { // 起始处可不用判断isVaild
                    if (dfs(board, visited, i, j, 0, word)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private static boolean dfs(char[][] board, boolean visited[][], int i, int j, int pos,
            String word) {
        if (pos == word.length() - 1) {
            return true;
        }

        int[] dx = { 0, 0, -1, 1 };
        int[] dy = { -1, 1, 0, 0 };

        visited[i][j] = true;// 进入本点再置本点为已访问,而不是在外面一层处理,避免写两遍。两者效果相同,目的均在于不对其他前缀的路径有影响。
        for (int t = 0; t < 4; ++t) {
            int x = i + dx[t];
            int y = j + dy[t];
            if (isVaild(board, visited, x, y) && board[x][y] == word.charAt(pos + 1)) { //
                if (dfs(board, visited, x, y, pos + 1, word)) {
                    return true;
                }
            }
        }
        visited[i][j] = false;
        return false;
    }

    private static boolean isVaild(char[][] board, boolean[][] visited, int i, int j) {
        return i >= 0 && i < board.length && j >= 0 && j < board[0].length && !visited[i][j];
    }
}

猜你喜欢

转载自www.cnblogs.com/coding-gaga/p/12072355.html