Sunday, September 21, 2014

LeetCode: Word Search

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.



 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
   typedef vector<vector<bool> > vvb;  
   typedef vector<vector<char> > vvc;  
   
   bool backtrack(vvc &board, string &word, int i, int j, int x, int n, int row, int col, vvb &visited)  
   {  
     if(x == n && word[x] == board[i][j])return true;  
     if (word[x] != board[i][j]) return false;  
       
     bool left = false, right = false, up = false, down = false;  
     visited[i][j] = true;  
     if (j > 0 && visited[i][j-1] == false){  
       left = backtrack(board, word, i, j-1, x+1, n, row, col, visited);  
       if (left) return true;  
     }  
   
     if (j < col && visited[i][j+1] == false){  
       right = backtrack(board, word, i, j+1, x+1, n, row, col, visited);  
       if (right) return true;  
     }  
   
     if (i > 0 && visited[i-1][j] == false){  
       up = backtrack(board, word, i-1, j, x+1, n, row, col, visited);  
       if (up) return true;  
     }  
       
     if (i < row && visited[i+1][j] == false){  
       down = backtrack(board, word, i+1, j, x+1, n, row, col, visited);  
       if (down) return true;  
     }  
     visited[i][j] = false;  
     return false;  
   }  
   
   bool exist(vector<vector<char> > &board, string word) {  
     int n = word.length();  
     if(!n)return false;  
     int row = board.size();  
     if(!row) return false;  
     int col = board[0].size();  
     if(row*col < n)return false;  
   
     vvb visited(row, vector<bool>(col, false));   
     for (int i = 0; i < row; i++)  
     {  
       for(int j = 0; j < col; j++)  
       {  
         if(board[i][j] == word[0] && backtrack(board, word, i , j, 0,n-1, row-1, col-1, visited))return true;  
       }  
     }  
     return false;  
   } 

No comments:

Post a Comment