-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathWordSearchII.cpp
More file actions
61 lines (55 loc) · 1.87 KB
/
Copy pathWordSearchII.cpp
File metadata and controls
61 lines (55 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Solution {
public:
struct TrieNode {
TrieNode *children[26];
string word;
TrieNode(): word("") {
for(int i=0; i<26; i++) {
children[i] = nullptr;
}
}
};
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
TrieNode *root = buildTrie(words);
vector<string> result;
for(int i=0; i< board.size(); i++) {
for(int j=0; j<board[0].size(); j++) {
dfs(board, i, j, root, result);
}
}
return result;
}
// Inserts a word into the trie
TrieNode *buildTrie(vector<string> &words) {
TrieNode *root = new TrieNode();
for(int j=0; j < words.size(); j++) {
string word = words[j];
TrieNode *curr = root;
for(int i=0; i < word.size(); i++) {
char c = word[i] - 'a';
if(curr->children[c] == nullptr) {
curr->children[c] = new TrieNode();
}
curr = curr->children[c];
}
curr->word = word;
}
return root;
}
void dfs(vector<vector<char>> &board, int i, int j, TrieNode *p, vector<string> &result) {
char c = board[i][j];
// this is the base condition, i.e. when there is already a value in board[i][j]
if(c == '#' || !p->children[c - 'a']) return;
p = p->children[c - 'a'];
if(p->word.size() > 0) {
result.push_back(p->word);
p->word = "";
}
board[i][j] = '#';
if(i > 0) dfs(board, i-1, j, p, result);
if(j > 0) dfs(board, i, j-1, p, result);
if(i < board.size() - 1) dfs(board, i + 1, j, p, result);
if(j < board[0].size() - 1) dfs(board, i, j+1, p, result);
board[i][j] = c;
}
};