From 04feff84787ee65fd25b6e5df4141f4787f662a5 Mon Sep 17 00:00:00 2001 From: Fazeel Usmani Date: Sat, 9 Oct 2021 23:58:13 +0530 Subject: [PATCH] Create 09_word-searchii.cpp --- .../09_word-searchii.cpp | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 10 October LeetCode Challenge 2021/09_word-searchii.cpp diff --git a/10 October LeetCode Challenge 2021/09_word-searchii.cpp b/10 October LeetCode Challenge 2021/09_word-searchii.cpp new file mode 100644 index 0000000..a411a85 --- /dev/null +++ b/10 October LeetCode Challenge 2021/09_word-searchii.cpp @@ -0,0 +1,65 @@ +class Trie{ +public: + string word; + bool is_word=false; + Trie* children[26]={NULL}; +}; + +class Solution { +private: + Trie* root=NULL; + + void insert(string &s){ + Trie* temp=root; + for(auto &i:s){ + int k=i-'a'; + if(temp->children[k]==NULL){ + temp->children[k]=new Trie; + } + temp=temp->children[k]; + } + temp->word=s; + temp->is_word=true; + } + + void dfs(vector>&board, vector&res, Trie* temp, int i, int j){ + + if(i<0 || i>=board.size() || j<0 || j>=board[0].size() || board[i][j]=='*' || !(temp->children[board[i][j]-'a'])) + return; + + temp=temp->children[board[i][j]-'a']; + + if(temp->is_word){ + res.push_back(temp->word); + temp->is_word=false; + } + + char temp_char = board[i][j]; + board[i][j]='*'; + + dfs(board, res, temp, i+1, j); + dfs(board, res, temp, i, j+1); + dfs(board, res, temp, i-1, j); + dfs(board, res, temp, i, j-1); + + board[i][j]=temp_char; + + return; + } + +public: + Solution(){ + root=new Trie; + } + vector findWords(vector>& board, vector& words) { + for(auto &s:words) + insert(s); + vectorres; + Trie* temp=root; + + for(int i=0;i