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
     
  • 相关阅读:
    发送http请求时,如果token过期了会返回什么
    遍历某个文件夹下所有的文件
    写出冒泡排序的算法
    sql,学生表(student),id,name ,age ,求前10个年龄最大的
    给一个无序数组,输出这个数组的前n个最大的
    python随机数模块random
    java --String、StringBuffer、StringBuilder
    java内存空间
    第四次寒假作业
    寒假作业3
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13264089.html
Copyright © 2011-2022 走看看