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
     
  • 相关阅读:
    Js学习第十天----函数
    IOS Object和javaScript相互调用
    hadoop2.7.1 nutch2.3 二次开发windows环境
    交叉熵代价函数(作用及公式推导)
    推断dxf文件的版本号
    mahout in Action2.2-聚类介绍-K-means聚类算法
    Xcode 技巧充电篇
    Android 推断SD卡是否存在及容量查询
    springmvc学习笔记(12)-springmvc注解开发之包装类型參数绑定
    pip简单配置
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13264089.html
Copyright © 2011-2022 走看看