|
| 1 | +class Solution { |
| 2 | + struct node |
| 3 | + { |
| 4 | + char c; |
| 5 | + int ends; //can be bool to in this qurstion |
| 6 | + string word; |
| 7 | + node* child[26]; |
| 8 | + }; |
| 9 | + |
| 10 | + struct node* getNode(char c) |
| 11 | + { |
| 12 | + node *newnode = new node; |
| 13 | + newnode->c = c; |
| 14 | + newnode->ends = 0; |
| 15 | + newnode->word = ""; |
| 16 | + for(int i=0;i<26;i++) |
| 17 | + newnode->child[i] =NULL; |
| 18 | + return newnode; |
| 19 | + } |
| 20 | + |
| 21 | + node * root = getNode('/'); |
| 22 | + |
| 23 | + void insert(string s) |
| 24 | + { |
| 25 | + node *curr=root; |
| 26 | + int index,i=0; |
| 27 | + while(s[i]) |
| 28 | + { |
| 29 | + index = s[i]-'a'; |
| 30 | + if(curr->child[index]==NULL) |
| 31 | + curr->child[index] = getNode(s[i]); |
| 32 | + curr = curr->child[index]; |
| 33 | + i=i+1; |
| 34 | + } |
| 35 | + curr->ends=1; |
| 36 | + curr->word = s; |
| 37 | + } |
| 38 | + |
| 39 | + void solve(vector<vector<char>>& board, int i, int j, int r, int c, vector<string> &ans, node*curr) |
| 40 | + { |
| 41 | + int idx = board[i][j]-'a'; |
| 42 | + |
| 43 | + if(board[i][j] == '$' || curr->child[idx]==NULL) |
| 44 | + return; |
| 45 | + |
| 46 | + curr = curr->child[idx]; |
| 47 | + |
| 48 | + if(curr->ends > 0) |
| 49 | + { |
| 50 | + ans.push_back(curr->word); |
| 51 | + curr->ends -= 1; |
| 52 | + } |
| 53 | + |
| 54 | + char ch = board[i][j]; |
| 55 | + |
| 56 | + board[i][j] = '$'; |
| 57 | + if(i>0) |
| 58 | + solve(board, i-1, j, r,c, ans, curr); |
| 59 | + |
| 60 | + if(i<r-1) |
| 61 | + solve(board, i+1, j, r,c, ans, curr); |
| 62 | + if(j>0) |
| 63 | + solve(board, i, j-1, r,c, ans, curr); |
| 64 | + if(j<c-1) |
| 65 | + solve(board, i, j+1, r,c, ans, curr); |
| 66 | + board[i][j] = ch; |
| 67 | + } |
| 68 | + |
| 69 | +public: |
| 70 | + vector<string> findWords(vector<vector<char>>& board, vector<string>& words) |
| 71 | + { |
| 72 | + |
| 73 | + int r = board.size(); |
| 74 | + int c = board[0].size(); |
| 75 | + |
| 76 | + for(int i=0;i<words.size();i++) |
| 77 | + insert(words[i]); |
| 78 | + |
| 79 | + vector<string> ans; |
| 80 | + for(int i=0;i<r;i++) |
| 81 | + { |
| 82 | + for(int j=0;j<c;j++) |
| 83 | + solve(board, i, j, r, c, ans, root); |
| 84 | + } |
| 85 | + return ans; |
| 86 | + } |
| 87 | +}; |
0 commit comments