Online Judge Solutions

Tuesday, December 16, 2014

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.
Example
Given board =
[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
 
class Solution {
private:
   bool exist(vector > &board, int row, int col, string word, int pos) {
       if (pos >= word.length()) return true;
       if (row < 0 || row >= board.size() || col < 0 || col >= board[0].size()) return false;
       if (board[row][col] != word[pos]) return false;
       
       char origC = board[row][col];
       board[row][col] = -1;
       
       int offset[][2] = {{-1,0}, {1, 0}, {0, 1}, {0, -1}};
       bool found = false;
       for(int i =0 ; i < 4; i++) {
           if (exist(board, row+offset[i][0], col+offset[i][1], word, pos+1)) {
               found = true;
               break; 
           }
       }

       board[row][col] = origC;
       return found;
   }
public:
    /**
     * @param board: A list of lists of character
     * @param word: A string
     * @return: A boolean
     */
    bool exist(vector > &board, string word) {
       for(int i = 0; i < board.size(); i++)
          for(int j = 0; j < board[0].size(); j++)
             if (exist(board, i,j, word, 0)) return true;
        return false;
    }
};

No comments:

Post a Comment