Friday, January 24, 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.
This is almost the same as the question I met before while interviewed by Google for the last round. However, still a little bit difference. Will talk about this later.
Algorithm:
1. For search board problem, it is convenient to use recursion to solve the problem.
2. pay attention to the termination of recursion. The order of the termination matters.
3. easy-to-messed-up details are coloured red in the code.
4. Should set the visited back to false if the current visit is not validate.
Attention:
Firstly got wrong on passing the 2D array of visited, the way I test correctly now is to use a ** pointer and set the value first separately.
My code:
bool searchword(vector> &board, int h, int w, int i, int j, 
                    string word, int wordpos, bool **visited){
         if(wordpos == word.length()) return true;
         if(i < 0 || i > h-1 || j < 0 || j > w-1) return false;
         if(board[i][j] != word[wordpos] || visited[i][j] == true) return false;
         visited[i][j] = true;
         if(searchword(board, h, w, i+1, j, word, wordpos+1, visited)) 
           return true;
         if(searchword(board, h, w, i-1, j, word, wordpos+1, visited)) 
           return true;
         if(searchword(board, h, w, i, j+1, word, wordpos+1, visited)) 
           return true;
         if(searchword(board, h, w, i, j-1, word, wordpos+1, visited)) 
           return true;
         visited[i][j] = false;
         return false;
        }
    bool exist(vector > &board, string word) {
        if(word.empty()) return false;
        if(board.empty()) return false;
        int h = board.size();
        int w = board[0].size();
        bool **visited;
        visited = new bool *[h];
        for(int i = 0; i < h; i++)
            visited[i] = new bool[w];
        for(int i = 0; i < h; i++)
          for(int j = 0; j < w; j++)
            visited[i][j] = false;
        for(int i = 0;i < h; i++){
            for(int j = 0; j < w; j++){
                if(board[i][j] == word[0]){
                    if(searchword(board, h, w, i, j, word, 0, visited))
                        return true;
                }
            }
        }
        return false;
    }

No comments:

Post a Comment