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 =

[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

答案

class Solution {
    public boolean exist(char[][] board, String word) {
        int rows = board.length, cols = board[0].length;
        boolean[][] visited = new boolean[rows][cols];
        for(int i = 0; i < rows; i++) {
            for(int j = 0; j < cols; j++) {
                if(word.charAt(0) == board[i][j] && exist(board, visited, word, i, j, 0)) 
                    return true;
            }
        }
        return false;
    }
    private boolean exist(char[][] board, boolean[][] visited, String word, int i, int j, int step) {
        if(step == word.length()) return true;
        if(i < 0 || i >= board.length || j < 0 || j >= board[0].length || visited[i][j] || word.charAt(step) != board[i][j])
            return false;

        visited[i][j] = true;
        boolean ret = exist(board, visited, word, i - 1, j, step + 1) 
            || exist(board, visited, word, i + 1, j, step + 1) 
            || exist(board, visited, word, i, j - 1, step + 1)
            || exist(board, visited, word, i, j + 1, step + 1);
        visited[i][j] = false;
        return ret;
    }
}

你可能感兴趣的:(Word Search)