forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0212-word-search-ii.cpp
89 lines (70 loc) · 2.32 KB
/
0212-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
/*
Given a board of characters & a list of words, return all words on the board
Implement trie, for search: iterate thru children until isWord, add to result
Time: O(m x (4 x 3^(l - 1))) -> m = # of cells, l = max length of words
Space: O(n) -> n = total number of letters in dictionary (no overlap in Trie)
*/
class TrieNode {
public:
TrieNode* children[26];
bool isWord;
TrieNode() {
for (int i = 0; i < 26; i++) {
children[i] = NULL;
}
isWord = false;
}
};
class Solution {
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
for (int i = 0; i < words.size(); i++) {
insert(words[i]);
}
int m = board.size();
int n = board[0].size();
TrieNode* node = root;
vector<string> result;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
search(board, i, j, m, n, node, "", result);
}
}
return result;
}
private:
TrieNode* root = new TrieNode();
void insert(string word) {
TrieNode* node = root;
int curr = 0;
for (int i = 0; i < word.size(); i++) {
curr = word[i] - 'a';
if (node->children[curr] == NULL) {
node->children[curr] = new TrieNode();
}
node = node->children[curr];
}
node->isWord = true;
}
void search(vector<vector<char>>& board, int i, int j, int m, int n, TrieNode* node, string word, vector<string>& result) {
if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] == '#') {
return;
}
char c = board[i][j];
node = node->children[c - 'a'];
if (node == NULL) {
return;
}
word += board[i][j];
if (node->isWord) {
result.push_back(word);
node->isWord = false;
}
board[i][j] = '#';
search(board, i - 1, j, m, n, node, word, result);
search(board, i + 1, j, m, n, node, word, result);
search(board, i, j - 1, m, n, node, word, result);
search(board, i, j + 1, m, n, node, word, result);
board[i][j] = c;
}
};