Monday, October 19, 2015

[leetcode] Word Search

这条题意思是 寻找2d arry里面有没有 字母通过连接上下左右邻居且不重复的情况下 存在一个单词
每格 作为一个起点 用DFS搜索, 就是用DFS 上下左右 走个遍... 看看每格的字母 是不是 跟string.charAt(index)一样凡是出界,已经走过,不相等 直接return false
代码很直观
public class Solution {
    String word;
    char[][] board;
    boolean checked[][];
    public boolean exist(char[][] board, String word) {
        checked = new boolean[board.length][board[0].length];
        this.word = word;
        this.board = board;
        for (int i = 0; i < board.length; i++){
            for (int j = 0; j < board[0].length; j++){
                if (recursiveSol(i,j,0)){
                    return true;
                }
            }
        }
        
        return false;
    }
    
    boolean recursiveSol(int row, int column, int index){
        if (row >= board.length || 
            column >= board[0].length ||
            row < 0 ||
            column < 0 ||
            word.charAt(index) != board[row][column] ||
            checked[row][column]){
            return false;
        }
        
        if (word.charAt(index) == board[row][column] && index == word.length()-1){
            return true;
        }
        
        checked[row][column] = true;
        boolean result = false;
        if (recursiveSol(row+1, column, index+1) || recursiveSol(row-1, column, index+1) 
         || recursiveSol(row, column+1, index+1) || recursiveSol(row, column-1, index+1)){
            return true;
        }

        checked[row][column] = false;
        return false;
    }
}

No comments:

Post a Comment