212. Word Search II
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example:
Input:
words = ["oath","pea","eat","rain"] and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
Output: ["eat","oath"]
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
class TrieNode {
public:
vector<TrieNode*> next;
string word;
TrieNode() : word(""), next(vector<TrieNode*>(26, nullptr)){}
~TrieNode() {
for (TrieNode*& child : next) {
if (child) delete child;
}
}
};
TrieNode* buildTrie(vector<string>& words) {
TrieNode* root = new TrieNode();
for (string& w : words) {
TrieNode* cur = root;
for (char c : w) {
int idx = c - 'a';
if (!cur->next[idx]) cur->next[idx] = new TrieNode();
cur = cur->next[idx];
}
cur->word = w;
}
return root;
}
void helper(vector<vector<char> >& board, int i, int j, TrieNode* cur, vector<string>& res) {
if (i < 0 || i >= board.size() || j < 0 || j >= board[0].size() || board[i][j] == '#' || !cur->next[board[i][j] - 'a']) return;
char c = board[i][j];
cur = cur->next[c - 'a'];
if (!cur->word.empty()) {
res.push_back(cur->word);
cur->word.clear();
}
board[i][j] = '#';
helper(board, i - 1, j, cur, res);
helper(board, i + 1, j, cur, res);
helper(board, i, j - 1, cur, res);
helper(board, i, j + 1, cur, res);
board[i][j] = c;
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) { // time: (m * n * 4^(average word length)); space: O(4^(average word length))
vector<string> res;
if (board.empty() || board[0].empty() || words.empty()) return res;
TrieNode* root = buildTrie(words);
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[0].size(); ++j) {
helper(board, i, j, root, res);
}
}
return res;
}
Last updated
Was this helpful?