JunyiCode
3/29/2020 - 3:11 PM

79. Word Search

DFS 489 695 island

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