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
     
  • 相关阅读:
    “Win10 UAP 开发系列”之 在MVVM模式中控制ListView滚动位置
    “Win10 UAP 开发系列”之主题模式切换
    Windows Phone 8.1中AppBarToggleButton的绑定问题
    Windows Phone 8.1中处理后退键的HardwareButtons.BackPressed事件
    在后台代码中动态生成pivot项并设置EventTrigger和Action的绑定
    数据对象转json与md5加密注意事项
    iOS中wkwebview加载本地html的要点
    iOS项目开发常用功能静态库
    AFN中请求序列化的设置
    swift中的AnyHashable
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13264089.html
Copyright © 2011-2022 走看看