-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.cpp
62 lines (57 loc) · 1.65 KB
/
Solution.cpp
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
62
class Trie {
public:
vector<Trie*> children;
int ref;
Trie()
: children(26, nullptr)
, ref(-1) {}
void insert(const string& w, int ref) {
Trie* node = this;
for (char c : w) {
c -= 'a';
if (!node->children[c]) {
node->children[c] = new Trie();
}
node = node->children[c];
}
node->ref = ref;
}
};
class Solution {
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
Trie* tree = new Trie();
for (int i = 0; i < words.size(); ++i) {
tree->insert(words[i], i);
}
vector<string> ans;
int m = board.size(), n = board[0].size();
function<void(Trie*, int, int)> dfs = [&](Trie* node, int i, int j) {
int idx = board[i][j] - 'a';
if (!node->children[idx]) {
return;
}
node = node->children[idx];
if (node->ref != -1) {
ans.emplace_back(words[node->ref]);
node->ref = -1;
}
int dirs[5] = {-1, 0, 1, 0, -1};
char c = board[i][j];
board[i][j] = '#';
for (int k = 0; k < 4; ++k) {
int x = i + dirs[k], y = j + dirs[k + 1];
if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] != '#') {
dfs(node, x, y);
}
}
board[i][j] = c;
};
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
dfs(tree, i, j);
}
}
return ans;
}
};