欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

79. Word Search

程序员文章站 2022-07-14 17:30:39
...

Description

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 =

[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

Solution

DFS

class Solution {
    public boolean exist(char[][] board, String word) {
        if (board == null || word == null) {
            return false;
        }
        
        if (word.isEmpty()) {
            return true;
        }
        
        if (0 == board.length || 0 == board[0].length) {
            return false;
        }
        
        int m = board.length;
        int n = board[0].length;
        boolean[][] used = new boolean[m][n];
        
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (existRecur(board, i, j, word, 0, used)) {
                    return true;
                }
            }
        }
        
        return false;
    }
    
    public boolean existRecur(char[][] board, int i, int j
                              , String word, int len, boolean[][] used) {
        if (word.length() <= len) {
            return true;
        }
        
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) {
            return false;
        }
        
        if (board[i][j] != word.charAt(len) || used[i][j]) {
            return false;
        }
        
        used[i][j] = true;
        boolean exist = existRecur(board, i - 1, j, word, len + 1, used)
            || existRecur(board, i + 1, j, word, len + 1, used)
            || existRecur(board, i, j - 1, word, len + 1, used)
            || existRecur(board, i, j + 1, word, len + 1, used);
        used[i][j] = false;
        return exist;
    }
}