LeetCode每日一题:word search

问题描述

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.
For example,
Given board =
[
["ABCE"],
["SFCS"],
["ADEE"]
]
word ="ABCCED", -> returns true,
word ="SEE", -> returns true,
word ="ABCB", -> returns false.

问题分析

这题其实考察的就是DFS,对于一个位置,只要dfs上下左右四个角就行了,由于不能重复使用,所以要用一个数组isUsed来存储是否已经遍历过了。

代码实现

public boolean exist(char[][] board, String word) {
        if (word.length() == 0) return true;
        if (board.length == 0 || board[0].length == 0) return false;
        boolean[][] isUsed = 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 (dfsSearchWord(board, word, 0, i, j, isUsed)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfsSearchWord(char[][] board, String word,
                                  int depth, int row, int col, boolean[][] isUsed) {
        if (depth == word.length()) return true;
        if (row < 0 || col < 0 || row >= board.length || col >= board[0].length) return false;
        if (isUsed[row][col]) return false;
        if (board[row][col] != word.charAt(depth)) return false;
        isUsed[row][col] = true;
        boolean result = dfsSearchWord(board, word, depth + 1, row - 1, col, isUsed)
                || dfsSearchWord(board, word, depth + 1, row + 1, col, isUsed)
                || dfsSearchWord(board, word, depth + 1, row, col - 1, isUsed)
                || dfsSearchWord(board, word, depth + 1, row, col + 1, isUsed);
        //搜索上下左右四个角
        isUsed[row][col] = false;
        return result;
    }

你可能感兴趣的:(LeetCode每日一题:word search)