AviatorJeremy

[leetcode]79.word search

class Solution {
    boolean[][] used;
    public boolean exist(char[][] board, String word) {
        used = new boolean[board.length][board[0].length];
        for(int i = 0; i < board.length; i++) {
            for(int j = 0; j < board[i].length; j++) {
                if (board[i][j] == word.charAt(0))
                    if(DFS(board, word, i, j, 0))
                        return true;
                else
                    continue;
            }
        }
        return false;
    }
    
    public boolean DFS(char[][] board, String word, int i, int j, int index) {
        if (i < 0 || j < 0 || i >= board.length || j >= board[i].length || word.charAt(index) != board[i][j] || used[i][j]) {
            return false;
        }
        else if (index == word.length() - 1) {
            return true;
        } else {
            used[i][j] = true;
            if(DFS(board, word, i, j+1, index+1) || DFS(board, word, i+1, j, index+1) || DFS(board, word, i, j-1, index+1) || DFS(board, word, i-1, j, index+1)) {
                return true;
            } else {
                used[i][j] = false;
                return false;
            }
        }
    }
    
}

  

 

posted on 2018-08-31 17:00  AviatorJeremy  阅读(111)  评论(0编辑  收藏  举报

导航