atulsingh7890

Word Search

Oct 21st, 2020
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. //https://leetcode.com/problems/word-search/
  2. class Solution {
  3. public:
  4.     bool exist(vector<vector<char>>& board, string word) {
  5.        
  6.         for(int i = 0; i < board.size(); ++i) {
  7.             for(int j = 0; j < board[i].size(); ++j) {
  8.                 if(board[i][j] == word[0]) {
  9.                     std::vector<std::vector<bool>> visited_array(board.size(), std::vector<bool>(board[0].size(), false));
  10.                     bool word_exists =  exists(board, visited_array, i,j, word, 0);
  11.                     if(word_exists)
  12.                         return true;
  13.                    
  14.                 }
  15.             }
  16.         }
  17.         return false;
  18.     }
  19. private:
  20.     bool exists(std::vector<std::vector<char>> &board, std::vector<std::vector<bool>> & visited_array, int r, int c, std::string & word, int current_index) {
  21.         if(current_index == word.size())
  22.             return true;
  23.        
  24.         if(r < 0 || r >= board.size())
  25.             return false;
  26.         if(c <0 || c >= board[0].size())
  27.             return false;
  28.        
  29.         if(board[r][c] == word[current_index] && visited_array[r][c] == false) {
  30.             visited_array[r][c] = true;            
  31.             bool is_whole_word_present = exists(board, visited_array, r+1,c, word, current_index+1) ||
  32.                 exists(board, visited_array, r,c+1, word, current_index+1) ||
  33.                 exists(board, visited_array, r-1,c, word, current_index+1) ||
  34.                 exists(board, visited_array, r,c-1, word, current_index+1);
  35.             if(is_whole_word_present)
  36.                 return true;
  37.             visited_array[r][c] = false;
  38.         }
  39.        
  40.         return false;
  41.        
  42.     }
  43.    
  44. };
Add Comment
Please, Sign In to add comment