-
Notifications
You must be signed in to change notification settings - Fork 0
/
212. Word Search II.cpp
99 lines (80 loc) · 2.12 KB
/
212. Word Search II.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// https://leetcode.com/problems/word-search-ii/
class TrieNode
{
public:
char val;
TrieNode *children[26] = {nullptr};
bool isWord;
string word;
TrieNode()
{
this->isWord = false;
}
TrieNode(char val)
{
this->val = val;
this->isWord = false;
}
};
class Trie
{
public:
TrieNode *root;
Trie()
{
root = new TrieNode();
}
void insert(string word)
{
TrieNode *current = root;
for (char &c : word)
{
if (current->children[c - 'a'] == nullptr)
current->children[c - 'a'] = new TrieNode(c);
current = current->children[c - 'a'];
}
current->isWord = true;
current->word = word;
}
void dfs(vector<string> &result, vector<vector<char>> &board, int i, int j, TrieNode *current)
{
if (current->isWord)
{
result.push_back(current->word);
current->isWord = false;
current->word = "";
}
if (i < 0 || i >= board.size() || j < 0 || j >= board[i].size() || board[i][j] == '.')
return;
if (current->children[board[i][j] - 'a'] != nullptr)
{
char temp = board[i][j];
board[i][j] = '.';
dfs(result, board, i + 1, j, current->children[temp - 'a']);
dfs(result, board, i - 1, j, current->children[temp - 'a']);
dfs(result, board, i, j + 1, current->children[temp - 'a']);
dfs(result, board, i, j - 1, current->children[temp - 'a']);
board[i][j] = temp;
}
}
};
class Solution
{
vector<string> result;
public:
vector<string> findWords(vector<vector<char>> &board, vector<string> &words)
{
Trie *trie = new Trie();
for (string &word : words)
trie->insert(word);
for (int i = 0; i < board.size(); ++i)
{
for (int j = 0; j < board[i].size(); j++)
{
TrieNode *current = trie->root;
trie->dfs(result, board, i, j, current);
}
}
return result;
}
};