leetcode79 - Word Search - medium

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;
    }
}

 

转载于:https://www.cnblogs.com/jasminemzy/p/9655942.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值