Search This Blog

Wednesday, January 16, 2013

LeetCode:Word Search

Word SearchApr 18 '12
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 =
[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]
word = "ABCCED", -> returns true, word = "SEE", -> returns true, word = "ABCB", -> returns false.
DFS and use a boolean array to keep track if one coordinate was visited or not.

public class Solution {
    public boolean exist(char[][] board, String word) {
        // Start typing your Java solution below
        // DO NOT write main() function
        
        if(word==null || word.length()==0) return true;
        
        int m = board.length,
            n = board[0].length;
        char[] letters = word.toCharArray();
        boolean[][] tried = new boolean[m][n];
        
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(board[i][j]==letters[0]){
                    tried = new boolean[m][n];
                    Stack<Integer[]> toVisit = new Stack<Integer[]>();
                    Integer[] temp = new Integer[2];
                    temp[0]=i*n+j; 
                    temp[1]=0;
                    toVisit.push(temp);
                    
                    
                    while(!toVisit.isEmpty()){
                        Integer[] cur = toVisit.pop();
                        if(!tried[cur[0]/n][cur[0]%n] && board[cur[0]/n][cur[0]%n]==letters[cur[1]]){
                            if(cur[1]==word.length()-1) return true;
                            tried[cur[0]/n][cur[0]%n]=true;
                            
                            for(int ii=-1;ii<=1;ii++){
                                for(int jj=-1;jj<=1;jj++){
                                    if((ii==0||jj==0) && cur[0]/n+ii>=0 && cur[0]/n+ii<m && cur[0]%n+jj>=0 && cur[0]%n+jj<n && !tried[cur[0]/n+ii][cur[0]%n+jj]){
                                        Integer[] temp1 = new Integer[2];
                                        temp1[0]=cur[0]/n*n+ii*n+cur[0]%n+jj;
                                        temp1[1]=cur[1]+1;
                                        toVisit.push(temp1);
                                    }
                                }
                            }
                            
                        }
                    }                 
                }
            }
        }
        return false;
        
    }
}

No comments: