zoukankan      html  css  js  c++  java
  • leetcode79

    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.

    DFS. (不可BFS)
    因为同一个字符不能用两遍的限制,不能用BFS做只能用DFS做。因为层级遍历的BFS会出现同时两个同样的字符一起出去进行搜索,那么两个的isVisited会互相干扰,可能A1占用了某条路径上的一些元素,其实A2也是要用到的,但因为isVisited的原因就不能用了。
    对每个以word第一个字符开头的位置去dfs,注意传一个新的isVisited下去。在四个方向尝试去递归之前要set一下isVisited,递归回来后要回溯isVisited状态。

    实现:

    class Solution {
        public boolean exist(char[][] board, String word) {
            if (board == null || board.length == 0 || board[0].length == 0 || word == null || word.length() == 0) {
                return false;
            }
            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, 0, i, j, new boolean[board.length][board[0].length])) {
                        return true;
                    }
                }
            }
            return false;
        }
        
        // P1 DFS也因为每个位置只能用一次,要传递isVisited[][]
        private boolean dfs(char[][]board, String word, int offset, int x, int y, boolean[][] isVisited) {
            if (!isValid(board, x, y) || board[x][y] != word.charAt(offset) || isVisited[x][y]) {
                return false;
            }
            if (offset == word.length() - 1) {
                return true;
            }
            
            int[] dx = {0, 1, 0, -1};
            int[] dy = {1, 0, -1, 0};
            boolean ans = false;
            isVisited[x][y] = true;
            for (int i = 0; i < 4; i++) {
                ans = ans || dfs(board, word, offset + 1, x + dx[i], y + dy[i], isVisited);
            }
            isVisited[x][y] = false;
            return ans;
        }
        
        private boolean isValid(char[][] board, int x, int y) {
            return x >= 0 && x < board.length && y >= 0 && y < board[0].length;
        }
    }
  • 相关阅读:
    [转]编程能力与编程年龄
    github for windows 使用
    github 改位置
    Linux下设置和查看环境变量
    Docker基础 :网络配置详解
    docker入门实战笔记
    Jenkins +Maven+Tomcat+SVN +Apache项目持续集成构建
    使用nsenter工具进入Docker容器
    Docker从入门到实战(四)
    Docker从入门到实战(三)
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9655942.html
Copyright © 2011-2022 走看看