其他分享
首页 > 其他分享> > leetcode 79. Word Search | 79. 单词搜索(回溯+DFS)

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

作者:互联网

题目

https://leetcode.com/problems/word-search/
在这里插入图片描述

题解

回溯 + 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;
    }
}

在这里插入图片描述

标签:index,Search,word,int,dfs,board,visited,Word,79
来源: https://blog.csdn.net/sinat_42483341/article/details/120634470