二刷Word Search

Medium
基本bug free吧,dfs.这道题的时间复杂度分析起来还是挺有意思的,第一次搜索第一个字母需要O(M*N),对于board里面的每个位置,我们都要从四个方向去搜索下一个位置。可以想象一棵quadtree,树上的每个节点就是board上的一个位置。比如

board = 
    [
      ['A','B','C','E'],
      ['S','F','C','S'],
      ['A','D','E','E']
    ]
word = "ABCCED"

那么这棵树的root就是board[0][0] = 'A',它的四个 children(toward 4 directions) 就是

board[0,1]="B"
board[1,0]="S"
board[0,-1]=no exist
board[-1,0]=no exist

这样的话,这棵quadtree的高度就是L(L is length of string word), 总节点数为4^0 + 4^1 + ... + 4^L = 1/3 * ( 4^(L+1) - 1 ). 所有time complexity of this dfs solution is O(M*N*4^L).然而因为我们做了visited[][]标记以及边界检查,所以并不会每次都访问所有的四个孩子,这样就不会让看起来恐怖的O(4^n) 导致TLE.

class Solution {
    public boolean exist(char[][] board, String word) {
        if (board == null || board.length == 0 || board[0].length == 0){
            return false;
        }
        boolean[][] visited = 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 (board[i][j] == word.charAt(0) && dfsHelper(board, i, j, word, visited, 0)){
                    return true;
                }
            }
        }
        return false;
    }
    
    private boolean dfsHelper(char[][] board, int i, int j, String word, boolean[][] visited, int index){
        if (index == word.length()){
            return true;
        }
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || visited[i][j] || word.charAt(index) != board[i][j]){
            return false;
        }    
        visited[i][j] = true;
        if (dfsHelper(board, i-1, j, word, visited, index+1) || dfsHelper(board, i+1, j, word, visited, index+1) ||
           dfsHelper(board, i, j+1, word, visited, index+1) || dfsHelper(board, i, j-1, word, visited, index+1)){
            return true;
        }
        visited[i][j] = false;
        return false;
    }
}

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