zoukankan      html  css  js  c++  java
  • 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
     
  • 相关阅读:
    Java 内存溢出(java.lang.OutOfMemoryError)的常见情况和处理方式总结
    Springmvc bean依赖注入为空
    protocol Buffer
    SSO单点登录
    .gitignore 不生效问题
    IntelliJ IDEA 背景色以及字体设置
    zookeeper 集群
    zookeeper 下载安装
    springboot 连接redis
    xshell 连接redis
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13264089.html
Copyright © 2011-2022 走看看