Saturday, May 10, 2014

Word Search -- Leetcode

Question:
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.
Answer:
class Solution {
public:
    bool exist(vector<vector<char> > &board, string word) {
        int m=board.size();
        int n=board[0].size();
        vector<vector<bool> > visited(m, vector<bool>(n,false) );
        
        for(int i=0;i<m;++i){
            for(int j=0;j<n;++j){
                if(board[i][j]==word[0]){
                    if(DFS(board,i,j,visited,0,word))
                        return true;
                }
            }
        }
        return false;
    }
    
    bool DFS(vector<vector<char>> &board, int i,int j,vector<vector<bool>> &visited,int index,string &word){  
        if(word[index]!=board[i][j])return false;
        
        //word[index] == board[i][j]
        if(index == word.length()-1){   //the last char of word, end case.
            visited[i][j]=true;
            return true;
        }
        else{
            visited[i][j]= true;
            
            if(j-1>=0 && !visited[i][j-1]){
               if(DFS(board,i,j-1,visited,index+1,word))
                   return true;
            }
            if(i-1>=0 && !visited[i-1][j]){
               if(DFS(board,i-1,j,visited,index+1,word))
                   return true;
            }
            if(j+1<board[0].size() && !visited[i][j+1]){
               if(DFS(board,i,j+1,visited,index+1,word))
                   return true;
            }
            if(i+1<board.size() && !visited[i+1][j]){
               if(DFS(board,i+1,j,visited,index+1,word))
                   return true;
            }
            
            visited[i][j] = false;   //backtrack!!!
        }
        return false;
    }

};

No comments:

Post a Comment