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;
        }
    }
  • 相关阅读:
    看了关于全职女性的文字,我想到了一些事情
    通过一个大型项目来学习分布式算法(6)
    IO模式——同步(堵塞、非堵塞)、异步
    湖南省第九届大学生计算机程序设计竞赛 高桥和低桥
    为什么我的ECSHOP出现报错改正确了还是没有反应?
    wxWidgets刚開始学习的人导引(2)——下载、安装wxWidgets
    1096. Consecutive Factors (20)
    POJ 2955 Brackets
    (转载)单调栈题目总结
    20140708郑州培训第二题Impossible Game
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9655942.html
Copyright © 2011-2022 走看看