leetcode 79. Word Search | 79. 单词搜索(回溯+DFS)

题目

https://leetcode.com/problems/word-search/
leetcode 79. Word Search | 79. 单词搜索(回溯+DFS)

题解

回溯 + DFS,回溯是有后效性的,所以不能转化为 DP

class Solution {
    int M;
    int N;

    public boolean exist(char[][] board, String word) {
        M = board.length;
        N = board[0].length;
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                if (dfs(word, 0, i, j, board, new boolean[M][N])) return true;
            }
        }
        return false;
    }

    public boolean dfs(String word, int index, int i, int j, char[][] board, boolean[][] visited) {
        if (index == word.length()) return true;
        if (i < 0 || i == M || j < 0 || j == N || visited[i][j] || board[i][j] != word.charAt(index)) return false;

        visited[i][j] = true;
        boolean result = dfs(word, index + 1, i + 1, j, board, visited) ||
                dfs(word, index + 1, i - 1, j, board, visited) ||
                dfs(word, index + 1, i, j + 1, board, visited) ||
                dfs(word, index + 1, i, j - 1, board, visited);
        visited[i][j] = false;

        return result;
    }
}

leetcode 79. Word Search | 79. 单词搜索(回溯+DFS)

上一篇:二分查找


下一篇:使用docker报错 :Error response from daemon: Get https://index.docker.io/v1/search?q=java&n=25: dial tcp: