|
| 1 | +class TrieNode{ |
| 2 | +public: |
| 3 | + TrieNode* children[26] = {}; |
| 4 | + string word = ""; |
| 5 | +}; |
| 6 | + |
| 7 | +class Solution { |
| 8 | +public: |
| 9 | + void insert(TrieNode* root, const string& word){ |
| 10 | + TrieNode* node = root; |
| 11 | + |
| 12 | + for(int i = 0; i < word.length(); i++){ |
| 13 | + int idx = word[i] - 'a'; |
| 14 | + |
| 15 | + if(!node->children[idx]) |
| 16 | + node->children[idx] = new TrieNode(); |
| 17 | + |
| 18 | + node = node->children[idx]; |
| 19 | + } |
| 20 | + node->word = word; |
| 21 | + } |
| 22 | + |
| 23 | + void dfs(int r, int c, vector<vector<char>>& board, TrieNode* root, vector<string>& result){ |
| 24 | + if(r < 0 || r >= board.size() || c < 0 || c >= board[r].size()) |
| 25 | + return; |
| 26 | + |
| 27 | + char ch = board[r][c]; |
| 28 | + |
| 29 | + if(ch == '#' || !root->children[ch - 'a']) |
| 30 | + return; |
| 31 | + |
| 32 | + root = root->children[ch - 'a']; |
| 33 | + |
| 34 | + if(!root->word.empty()){ |
| 35 | + result.push_back(root->word); |
| 36 | + root->word.clear(); |
| 37 | + } |
| 38 | + |
| 39 | + board[r][c] = '#'; |
| 40 | + |
| 41 | + dfs(r - 1, c, board, root, result); |
| 42 | + dfs(r + 1, c, board, root, result); |
| 43 | + dfs(r, c - 1, board, root, result); |
| 44 | + dfs(r, c + 1, board, root, result); |
| 45 | + |
| 46 | + board[r][c] = ch; |
| 47 | + } |
| 48 | + |
| 49 | + vector<string> findWords(vector<vector<char>>& board, vector<string>& words) { |
| 50 | + TrieNode* root = new TrieNode(); |
| 51 | + |
| 52 | + for(int i = 0; i < words.size(); i++) |
| 53 | + insert(root, words[i]); |
| 54 | + |
| 55 | + vector<string> result; |
| 56 | + |
| 57 | + for(int i = 0; i < board.size(); i++){ |
| 58 | + for(int j = 0; j < board[i].size(); j++){ |
| 59 | + dfs(i, j, board, root, result); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + return result; |
| 64 | + } |
| 65 | +}; |
0 commit comments