Given an m x n board of characters and a list of strings words, return all words on the board.
Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example 1:
Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"] Output: ["eat","oath"]
Example 2:
Input: board = [["a","b"],["c","d"]], words = ["abcb"] Output: []
Constraints:
m == board.lengthn == board[i].length1 <= m, n <= 12board[i][j] is a lowercase English letter.1 <= words.length <= 3 * 1041 <= words[i].length <= 10words[i] consists of lowercase English letters.words are unique.struct TrieNode {
TrieNode* children[26] = {};
string* word;
void addWord(string& word) {
TrieNode* cur = this;
for (char c : word) {
c -= 'a';
if (cur->children[c] == nullptr) cur->children[c] = new TrieNode();
cur = cur->children[c];
}
cur->word = &word;
}
};
class Solution {
public:
int m, n;
int DIR[5] = {0, 1, 0, -1, 0};
vector<string> ans;
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
m = board.size(); n = board[0].size();
TrieNode trieNode;
for (string& word : words) trieNode.addWord(word);
for (int r = 0; r < m; ++r)
for (int c = 0; c < n; ++c)
dfs(board, r, c, &trieNode);
return ans;
}
void dfs(vector<vector<char>>& board, int r, int c, TrieNode* cur) {
if (r < 0 || r == m || c < 0 || c == n || board[r][c] == '#' || cur->children[board[r][c]-'a'] == nullptr) return;
char orgChar = board[r][c];
cur = cur->children[orgChar - 'a'];
if (cur->word != nullptr) {
ans.push_back(*cur->word);
cur->word = nullptr; // Avoid duplication!
}
board[r][c] = '#'; // mark as visited!
for (int i = 0; i < 4; ++i) dfs(board, r + DIR[i], c + DIR[i+1], cur);
board[r][c] = orgChar; // restore org state
}
};