|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + |
| 4 | + struct trie{ |
| 5 | + trie* next[26]; |
| 6 | + int end; |
| 7 | + }; |
| 8 | + void insert( string word , trie* root ){ |
| 9 | + for ( char c : word){ |
| 10 | + if ( !root->next[c-'a'] ) root->next[c-'a'] = new trie(); |
| 11 | + root = root->next[c-'a']; |
| 12 | + } |
| 13 | + root->end =1; |
| 14 | + } |
| 15 | + |
| 16 | + void rec( vector<vector<int>> &vis , vector<vector<char>> &board , int x , int y , trie* root ,string curr, set<string> &ans ){ |
| 17 | + |
| 18 | + int n = board.size(); |
| 19 | + int m = board[0].size(); |
| 20 | + |
| 21 | + // base condition for return |
| 22 | + if (x < 0 || y < 0 || x >= n || y >= m ) return ; |
| 23 | + // already done in current recursion |
| 24 | + if ( vis[x][y] ) return; |
| 25 | + // if no such word exists it is useless to recurse |
| 26 | + if (!root || !root -> next[board[x][y] - 'a']) return ; |
| 27 | + |
| 28 | + root = root -> next[board[x][y]-'a']; |
| 29 | + curr.push_back(board[x][y]); |
| 30 | + if ( root->end == 1) |
| 31 | + ans.insert(curr); |
| 32 | + //however we still don't end recursion for words like "end" and "ending" |
| 33 | + |
| 34 | + vis[x][y] =1; |
| 35 | + rec( vis , board , x + 1, y , root ,curr , ans); |
| 36 | + rec( vis , board , x - 1, y , root ,curr , ans); |
| 37 | + rec( vis , board , x , y -1, root ,curr ,ans); |
| 38 | + rec( vis , board , x , y +1 , root ,curr , ans); |
| 39 | + vis[x][y] =0; |
| 40 | + curr.pop_back(); |
| 41 | + |
| 42 | + } |
| 43 | + |
| 44 | + |
| 45 | + |
| 46 | + vector<string> findWords(vector<vector<char>>& board, vector<string>& words) { |
| 47 | + trie * root = new trie(); |
| 48 | + for ( string word : words) { |
| 49 | + insert( word , root); |
| 50 | + } |
| 51 | + set<string> ans; |
| 52 | + string curr; |
| 53 | + int n = board.size(); |
| 54 | + int m = board[0].size(); |
| 55 | + vector<vector<int> > vis( n , vector<int> ( m , 0 )); |
| 56 | + for ( int i =0 ; i < n ; i++ ) |
| 57 | + for ( int j = 0 ; j < m ; j++) |
| 58 | + rec( vis ,board, i , j , root ,curr, ans); |
| 59 | + vector<string> ret; |
| 60 | + for ( string a : ans) |
| 61 | + ret.push_back(a); |
| 62 | + return ret; |
| 63 | + } |
| 64 | +}; |
0 commit comments