时间轴

2025-11-28

init


题目:


在Trie中保存字符串,这样避免递归时传递每次遍历的字符串。
用非递归的DFS版本对board的处理会有问题,DFS递归刚好符合回溯。

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <vector>
#include <string>
#include <unordered_map>
#include <unordered_set>

using std::string;
using std::vector;
using std::unordered_map;
using std::unordered_set;

struct TrieNode {
string word;
unordered_map<char, TrieNode *> children;
TrieNode()
{
this->word = "";
}
};

void insertTrie(TrieNode *root, const string &word)
{
TrieNode *node = root;
for (auto c : word) {
if (!node->children.count(c)) {
node->children[c] = new TrieNode();
}
node = node->children[c];
}
node->word = word;
}

class Solution {
public:
int dirs[4][2] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };

bool dfs(vector<vector<char> > &board, int x, int y, TrieNode *root, unordered_set<string> &res)
{
char ch = board[x][y];
if (!root->children.count(ch)) {
return false;
}
root = root->children[ch];
if (root->word.size() > 0) {
res.insert(root->word);
}

board[x][y] = '#';
for (int i = 0; i < 4; ++i) {
int nx = x + dirs[i][0];
int ny = y + dirs[i][1];
if (nx >= 0 && nx < board.size() && ny >= 0 && ny < board[0].size()) {
if (board[nx][ny] != '#') {
dfs(board, nx, ny, root, res);
}
}
}
board[x][y] = ch;

return true;
}

vector<string> findWords(vector<vector<char> > &board, vector<string> &words)
{
TrieNode *root = new TrieNode();
unordered_set<string> res;
vector<string> ans;

for (auto &word : words) {
insertTrie(root, word);
}
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[0].size(); ++j) {
dfs(board, i, j, root, res);
}
}

ans.assign(res.begin(), res.end());
return ans;
}
};