Advertisement
yash123321

Untitled

Oct 9th, 2021
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. class Solution {
  2.     struct Node{
  3.     public:
  4.         Node* child[26];
  5.         bool terminal=false;
  6.         string s;
  7.     };
  8.    
  9.     Node *root = new Node();  
  10.    
  11.     void insert(string st){
  12.         Node* temp = root;
  13.         for(char ch: st){
  14.             if(temp->child[ch-'a']==NULL){
  15.                 temp->child[ch-'a'] = new Node();
  16.             }
  17.             temp = temp->child[ch-'a'];
  18.         }
  19.         temp->terminal = true;
  20.         temp->s = st;
  21.     }
  22.    
  23.     void dfs(vector<vector<char>>& board, int i, int j, int r, int c, vector<string>& ans, Node *temp){
  24.         char ch = board[i][j];
  25.         if(board[i][j]=='$' || temp->child[ch-'a']==NULL) return;
  26.        
  27.         temp = temp->child[ch-'a'];
  28.         if(temp->terminal){
  29.             ans.push_back(temp->s);
  30.             temp->terminal = false;
  31.         }
  32.        
  33.         board[i][j] = '$';
  34.         if(i>0) dfs(board, i-1,j,r,c,ans,temp);
  35.         if(i<r-1) dfs(board, i+1,j,r,c,ans,temp);
  36.         if(j>0) dfs(board, i,j-1,r,c,ans,temp);
  37.         if(j<c-1) dfs(board, i,j+1,r,c,ans,temp);
  38.        
  39.         board[i][j] = ch;
  40.         return;
  41.     }
  42. public:
  43.     vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
  44.         for(int i=0; i<words.size(); i++){
  45.             insert(words[i]);
  46.         }
  47.        
  48.         vector<string> ans;
  49.         int r = board.size(), c= board[0].size();
  50.         for(int i=0; i<r; i++){
  51.             for(int j=0; j<c; j++){
  52.                 dfs(board,i,j,r,c,ans,root);
  53.             }
  54.         }
  55.         return ans;
  56.     }
  57. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement