forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
detonate-the-maximum-bombs.cpp
89 lines (87 loc) · 2.77 KB
/
detonate-the-maximum-bombs.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
// Time: O(|V|^2 + |V| * |E|)
// Space: O(|V| + |E|)
// bfs solution
class Solution {
public:
int maximumDetonation(vector<vector<int>>& bombs) {
vector<vector<int>> adj(size(bombs));
for (int i = 0; i < size(bombs); ++i) {
for (int j = 0; j < size(bombs); ++j) {
if (j == i) {
continue;
}
const int64_t dx = bombs[i][0] - bombs[j][0];
const int64_t dy = bombs[i][1] - bombs[j][1];
const int64_t r = bombs[i][2];
if (dx * dx + dy * dy <= r * r) {
adj[i].emplace_back(j);
}
}
}
int result = 0;
for (int i = 0; i < size(bombs); ++i) {
vector<int> q = {i};
unordered_set<int> lookup = {i};
while (!empty(q)) {
vector<int> new_q;
for (const auto& u : q) {
for (const auto& v : adj[u]) {
if (lookup.count(v)) {
continue;
}
lookup.emplace(v);
new_q.emplace_back(v);
}
}
q = new_q;
}
result = max(result, static_cast<int>(size(lookup)));
if (result == size(bombs)) {
break;
}
}
return result;
}
};
// Time: O(|V|^2 + |V| * |E|)
// Space: O(|V| + |E|)
// dfs solution
class Solution2 {
public:
int maximumDetonation(vector<vector<int>>& bombs) {
vector<vector<int>> adj(size(bombs));
for (int i = 0; i < size(bombs); ++i) {
for (int j = 0; j < size(bombs); ++j) {
if (j == i) {
continue;
}
const int64_t dx = bombs[i][0] - bombs[j][0];
const int64_t dy = bombs[i][1] - bombs[j][1];
const int64_t r = bombs[i][2];
if (dx * dx + dy * dy <= r * r) {
adj[i].emplace_back(j);
}
}
}
int result = 0;
for (int i = 0; i < size(bombs); ++i) {
vector<int> stk = {i};
unordered_set<int> lookup = {i};
while (!empty(stk)) {
const int u = stk.back(); stk.pop_back();
for (const auto& v : adj[u]) {
if (lookup.count(v)) {
continue;
}
lookup.emplace(v);
stk.emplace_back(v);
}
}
result = max(result, static_cast<int>(size(lookup)));
if (result == size(bombs)) {
break;
}
}
return result;
}
};