Timeline
Timeline
2025-11-28
init
Trie
Problem:
Store strings in the Trie to avoid passing the traversed string on each recursive call.
Using a non-recursive DFS version to handle the board can be problematic; recursive DFS fits backtracking well.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 | using std::string;using std::vector;using std::unordered_map;using std::unordered_set;struct TrieNode { string word; unordered_map<char, TrieNode *> children; TrieNode() { this->word = ""; }};void insertTrie(TrieNode *root, const string &word){ TrieNode *node = root; for (auto c : word) { if (!node->children.count(c)) { node->children[c] = new TrieNode(); } node = node->children[c]; } node->word = word;}class Solution { public: int dirs[4][2] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } }; bool dfs(vector<vector<char> > &board, int x, int y, TrieNode *root, unordered_set<string> &res) { char ch = board[x][y]; if (!root->children.count(ch)) { return false; } root = root->children[ch]; if (root->word.size() > 0) { res.insert(root->word); } board[x][y] = '#'; for (int i = 0; i < 4; ++i) { int nx = x + dirs[i][0]; int ny = y + dirs[i][1]; if (nx >= 0 && nx < board.size() && ny >= 0 && ny < board[0].size()) { if (board[nx][ny] != '#') { dfs(board, nx, ny, root, res); } } } board[x][y] = ch; return true; } vector<string> findWords(vector<vector<char> > &board, vector<string> &words) { TrieNode *root = new TrieNode(); unordered_set<string> res; vector<string> ans; for (auto &word : words) { insertTrie(root, word); } for (int i = 0; i < board.size(); ++i) { for (int j = 0; j < board[0].size(); ++j) { dfs(board, i, j, root, res); } } ans.assign(res.begin(), res.end()); return ans; }}; |
