-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWord_Search_II.cpp
More file actions
98 lines (84 loc) · 2.59 KB
/
Word_Search_II.cpp
File metadata and controls
98 lines (84 loc) · 2.59 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
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
class Solution {
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
vector<string> ans;
unordered_set<string> res;
r = board.size();
if(r <= 0) return ans;
c = board[0].size();
if(c <= 0) return ans;
trie = new TrieNode();
for(string word : words){
createTrie(word);
}
vector<vector<bool>> visited(r, vector<bool>(c,false));
for(int i = 0; i < r; i++){
for(int j = 0; j < c; j++){
dfs(board, res, visited, i, j, "");
}
}
for(string word : res){
ans.push_back(word);
}
return ans;
}
void dfs(vector<vector<char>>& board, unordered_set<string>& res,vector<vector<bool>>& visited, int i, int j, string str){
if(i >= board.size() || i < 0 || j >=board[0].size() || j < 0 || visited[i][j])
return ;
str += board[i][j];
int state = find(str);
if (state == 1) res.insert(str);
if (state == -1) return;
visited[i][j] = true;
dfs(board, res, visited, i-1, j, str);
dfs(board, res, visited, i+1, j, str);
dfs(board, res, visited, i, j+1, str);
dfs(board, res, visited, i, j-1, str);
visited[i][j] = false;
}
private:
static const int MAX = 26;
struct TrieNode{
TrieNode* next[MAX];
bool isEnd;
TrieNode() {
isEnd = false;
for(int i = 0; i < 26; i++)
next[i] = nullptr;
}
};
TrieNode* trie;
int r;
int c;
void createTrie(string &str){
const int len = str.length();
TrieNode *p = trie, *q;
for(int i = 0; i < len; i++){
int id = str[i]-'a';
if(p->next[id] == nullptr){
q = new TrieNode();
if(i == len-1) q->isEnd = true;
p->next[id] = q;
p = q;
}
else{
p = p->next[id];
}
}
p->isEnd = true;
}
int find(const string &str){ // 0 exists but not exactly is, 1 exactly is, -1 not exist at all
int len = str.length();
TrieNode* p = trie;
bool exist = false;
for(int i = 0; i < len; i++){
int id = str[i]-'a';
p = p->next[id];
if(!p){
return -1;
}
exist = true;
}
return p->isEnd ? 1 : 0;
}
};