Wednesday, March 11, 2015

79. Word Search Leetcode Java

79. Word Search Leetcode
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.
Solution:
Recursion. Check every char in the word from ind 0 to the last one. 
Base case/terminating case: if(ind==word.length()) ...
Recursion step:
check current index of the word and see if it is match to the char in the current position of the matrix, if no return false, if yes, recursively check all its neighbors with next character in the word. Mark the current position as visited. If all the chars can find a match during this recursion till the index reach the end of the word, return true, otherwise return false.
Tips:
Since it is word match, the matrix contains only alphabetic characters, so if the char in the current position is matched with the current index in the word, set the current char board[i][j]='*' and when it backtrack to current position, set it back to original value. board[i][j]=word.charAt(ind). Thus we can use this way to mark it as visited rather than use a 2-d boolean array and can save some space.
 public boolean exist(char[][] board, String word) {  
     if(board==null || board.length==0 || board[0].length==0) return false;  
     for(int i=0;i<board.length;i++){  
       for(int j=0;j<board[0].length;j++){  
         if(helper(board,i,j,0,word)) return true;  
       }  
     }  
     return false;  
   }  
   public boolean helper(char[][] board, int i, int j, int ind, String word){  
     if(ind==word.length()) return true;  
     if(i<0 || i>=board.length) return false;  
     if(j<0 || j>=board[0].length) return false;  
     if(board[i][j]==word.charAt(ind)) {  
       board[i][j]='*';  
       if(helper(board,i+1,j,ind+1,word) || helper(board,i-1,j,ind+1,word)||   
         helper(board,i,j-1,ind+1,word) || helper(board,i,j+1,ind+1,word)) return true;  
       board[i][j]=word.charAt(ind);  
     }  
     return false;  
   }  

No comments:

Post a Comment