-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path212.cpp
More file actions
64 lines (60 loc) · 1.92 KB
/
212.cpp
File metadata and controls
64 lines (60 loc) · 1.92 KB
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
class Solution {
public:
struct TrieNode{
struct TrieNode* child[26];
bool isEnd;
int idx;
TrieNode(){
isEnd = false;
idx = -1;
for(int i=0; i<26; i++)
child[i] = nullptr;
}
};
TrieNode* root;
vector<string> res;
void addWord(string key, int v) {
struct TrieNode* curr = root;
for(int i=0; i<key.size(); i++){
int idx = key[i]-'a';
if(!curr->child[idx])
curr->child[idx] = new TrieNode();
curr = curr->child[idx];
}
curr->isEnd = true;
curr->idx = v;
}
void dfs(TrieNode* parent, vector<vector<char>>& board, int i, int j , vector<string>& words){
if(i<0 || j<0 || i>=board.size() || j>=board[0].size()){
if(parent->isEnd && parent->idx!=-1){
res.push_back(words[parent->idx]);
parent->idx=-1;
}
return;
}
if(parent->isEnd && parent->idx!=-1){
res.push_back(words[parent->idx]);
parent->idx=-1;
}
for(int k=0; k<26; k++){
if(parent->child[k]!=nullptr && (k == (int)(board[i][j]-'a'))){
board[i][j] = '.';
dfs(parent->child[k],board,i+1,j,words);
dfs(parent->child[k],board,i,j+1,words);
dfs(parent->child[k],board,i-1,j,words);
dfs(parent->child[k],board,i,j-1,words);
board[i][j] = (char)(k+'a');
}
}
return;
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
root = new TrieNode();
for(int i=0; i<words.size(); i++)
addWord(words[i],i);
for(int i=0; i<board.size(); i++)
for(int j=0; j<board[0].size();j++)
dfs(root,board,i,j,words);
return res;
}
};