Skip to content

Commit 17c9817

Browse files
authored
Create 212.Word-Search-II_v2.cpp
1 parent 525da14 commit 17c9817

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
class Solution {
2+
class TrieNode
3+
{
4+
public:
5+
TrieNode* next[26];
6+
bool isEnd;
7+
int count = 0;
8+
TrieNode()
9+
{
10+
for (int i=0; i<26; i++)
11+
next[i]=NULL;
12+
isEnd=false;
13+
count=0;
14+
}
15+
};
16+
TrieNode* root;
17+
vector<string>rets;
18+
int M, N;
19+
bool visited[12][12];
20+
public:
21+
vector<string> findWords(vector<vector<char>>& board, vector<string>& words)
22+
{
23+
M=board.size();
24+
N=board[0].size();
25+
root=new TrieNode();
26+
for (int i=0; i<words.size(); i++)
27+
{
28+
TrieNode* node=root;
29+
for (auto ch: words[i])
30+
{
31+
if (node->next[ch-'a']==NULL)
32+
node->next[ch-'a']=new TrieNode();
33+
node=node->next[ch-'a'];
34+
node->count++;
35+
}
36+
node->isEnd=true;
37+
}
38+
39+
for (int i=0; i<M; i++)
40+
for (int j=0; j<N; j++)
41+
{
42+
TrieNode* node = root;
43+
string word;
44+
visited[i][j]=1;
45+
DFS(i,j,node,word,board);
46+
visited[i][j]=0;
47+
}
48+
49+
return rets;
50+
}
51+
52+
void DFS(int i, int j, TrieNode* node, string& word, vector<vector<char>>& board)
53+
{
54+
if (node->next[board[i][j]-'a']==NULL) return;
55+
if (node->next[board[i][j]-'a']->count==0) return;
56+
57+
node = node->next[board[i][j]-'a'];
58+
word.push_back(board[i][j]);
59+
60+
if (node->isEnd==true)
61+
{
62+
node->isEnd = false;
63+
rets.push_back(word);
64+
remove(root, word);
65+
}
66+
67+
vector<pair<int,int>>dir={{1,0},{-1,0},{0,1},{0,-1}};
68+
69+
for (int k=0; k<4; k++)
70+
{
71+
int x=i+dir[k].first;
72+
int y=j+dir[k].second;
73+
if (x<0||x>=M||y<0||y>=N) continue;
74+
if (visited[x][y]==1) continue;
75+
76+
visited[x][y]=1;
77+
DFS(x,y,node,word,board);
78+
visited[x][y]=0;
79+
}
80+
81+
word.pop_back();
82+
}
83+
84+
void remove(TrieNode* root, string word)
85+
{
86+
TrieNode* node = root;
87+
for (auto ch: word)
88+
{
89+
node = node->next[ch-'a'];
90+
node->count --;
91+
}
92+
}
93+
};

0 commit comments

Comments
 (0)