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;
        }
    }
  • 相关阅读:
    我藏在你的心里,你却不愿意寻找# BUG躲猫猫
    阴间需求之跨端登录
    神奇的props
    map与filter:你先我先?
    阴间BUG之动态路由刷新几率回首页
    阴间BUG之动态路由添加失败
    我在eltable就变了个模样,请你不要再想我,想起我
    SCP打包部署方法
    indexOf 与 includes
    YACC和BISON学习心得
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9655942.html
Copyright © 2011-2022 走看看