Skip to content

Commit 66934b3

Browse files
committed
212. Word Search II
1 parent e85e2e4 commit 66934b3

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

word-search-ii.cpp

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
//Runtime: 39 ms
2+
class Solution {
3+
public:
4+
vector<string>res;
5+
struct TrieNode
6+
{
7+
struct TrieNode* children[26];
8+
string word;
9+
};
10+
11+
TrieNode* NewNode()
12+
{
13+
TrieNode* node = new TrieNode;
14+
node->word = "";
15+
for(int i=0;i<26;i++)
16+
node->children[i] = NULL;
17+
return node;
18+
}
19+
20+
struct TrieNode* BuildTrie(vector<string>&words)
21+
{
22+
struct TrieNode* root = NewNode();
23+
for(string word:words)
24+
{
25+
TrieNode* crawl = root;
26+
for(char c:word)
27+
{
28+
if(crawl->children[c-'a'] == NULL)
29+
crawl->children[c-'a'] = NewNode();
30+
31+
crawl = crawl->children[c-'a'];
32+
}
33+
crawl->word = word;
34+
}
35+
36+
return root;
37+
}
38+
39+
40+
void solve(vector<vector<char> > &board, int i, int j, struct TrieNode* trie)
41+
{
42+
char c = board[i][j];
43+
if(c == '$' || !trie->children[c-'a'])
44+
return;
45+
46+
trie = trie->children[c-'a'];
47+
48+
if(trie->word != "")
49+
{
50+
res.push_back(trie->word);
51+
trie->word = "";
52+
}
53+
54+
board[i][j] = '$';
55+
56+
if(i>0)
57+
solve(board, i-1, j, trie);
58+
if(i<board.size()-1)
59+
solve(board, i+1, j, trie);
60+
if(j >0)
61+
solve(board, i, j-1, trie);
62+
63+
if(j<board[0].size() - 1)
64+
solve(board, i, j+1, trie);
65+
66+
board[i][j] = c;
67+
}
68+
69+
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
70+
struct TrieNode* trie = BuildTrie(words);
71+
72+
for(int i=0;i<board.size();i++)
73+
for(int j=0;j<board[0].size();j++)
74+
solve(board, i, j, trie);
75+
return res;
76+
}
77+
};

0 commit comments

Comments
 (0)