79. Word Search DFS矩阵中搜索单词

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

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

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.


整体思路:每个点都可以用作起点


数字岛需要有一个消灭标记的过程 visited[i] = false 又可以重复利用,所以再标记回true


(dfs的参数自己分析也似乎能自圆其说,但是和答案写的每次都不一样。看答案就觉得好有道理哦,就不得不放弃自己的写法,去背答案。

那也没啥办法,就是要不断地试错。就还是多对比 自己为啥错、多总结 正确答案的统一规律吧

递归的过程中,每次index都加1


到头了也没毛病,返回true

class Solution {
    public boolean exist(char[][] board, String word) {
        //cc
        if (board == null || board.length == 0 || word == null)
            return false;
        
        boolean[][] visited = new boolean[board.length][board[0].length];
        
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if ((board[i][j] == word.charAt(0)) && dfs(board, word, i, j, visited, 0))
                    return true;
            }
        }
        
        return false;
    }
    
    public boolean dfs(char[][] board, String word, int i, int j, boolean[][] visited,
                       int index) {
        //还要加个退出条件
        if (index == word.length())
            return true;
        
        //cc
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || visited[i][j] || (board[i][j] != word.charAt(index))) {
            return false;
        }
        
        visited[i][j] = true;
        if (dfs(board, word, i - 1, j, visited, index + 1) ||
        dfs(board, word, i + 1, j, visited, index + 1) ||
        dfs(board, word, i, j - 1, visited, index + 1) ||
        dfs(board, word, i, j + 1, visited, index + 1)) return true;
        visited[i][j] = false;
        
        return false;
    }
}
View Code
 
原文地址:https://www.cnblogs.com/immiao0319/p/13264089.html