vector<string> findWords(vector<vector<char> >& board, vector<string>& words) { vector<string> ans; if (board.empty() || board[0].empty() || words.empty()) return ans; TrieNode* root = buildTrieTree(words); for (int i=0; i<board.size(); i++) { for (int j=0; j<board[0].size(); j++) { if (root->getNext(board[i][j]) != NULL) { dfs(ans, board, i, j, root->getNext(board[i][j]), ""); } } } destroyTrieTree(root); return ans; }
TrieNode* buildTrieTree(vector<string>& words) { TrieNode* root = new TrieNode(); for (string word : words) { int index = 0; TrieNode* cur = root; while (index < word.size() && cur->getNext(word[index]) != NULL) { cur = cur->getNext(word[index]); index++; } while (index < word.size()) { cur->setNext(word[index]); cur = cur->getNext(word[index]); index++; } cur->setIsWord(true); } return root; }