4/12/2014

Leetcode -- Word Search

class Solution {  
 public:  
   bool exist(vector<vector<char> > &board, string word) {  
     for(int i = 0; i < board.size(); i++) {  
       for(int j = 0; j < board[i].size(); ++j) {  
         if(search(board, i, j, word)) {  
           return true;  
         }  
       }  
     }  
     return false;  
   }  
   bool search(vector<vector<char> >& board, int x, int y, string word) {  
     if(x >= board.size() || y >= board[0].size()) {  
       return word.empty();  
     }  
     if(board[x][y] == '0') {  
       return false;  
     }  
     if(word.length() == 1) {  
       return word[0] == board[x][y];  
     }  
     if(word[0] == board[x][y]) {  
       char temp = board[x][y];  
       board[x][y] = '0';  
       string newWord(word.substr(1));  
       bool ret = search(board, x - 1, y, newWord)   
         || search(board, x + 1, y, newWord)   
         || search(board, x, y + 1, newWord)   
         || search(board, x, y - 1, newWord);  
       if(!ret) {  
         board[x][y] = temp;  
       }  
       return ret;  
     }  
     return false;  
   }  
 };  

No comments: