[LeetCode] Detonate the Maximum Bombs

2101. Detonate the Maximum Bombs

You are given a list of bombs. The range of a bomb is defined as the area where its effect can be felt. This area is in the shape of a circle with the center as the location of the bomb.

The bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [xi, yi, ri]. xi and yi denote the X-coordinate and Y-coordinate of the location of the ith bomb, whereas ri denotes the radius of its range.

You may choose to detonate a single bomb. When a bomb is detonated, it will detonate all bombs that lie in its range. These bombs will further detonate the bombs that lie in their ranges.

Given the list of bombs, return the maximum number of bombs that can be detonated if you are allowed to detonate only one bomb.

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
class Solution {
long long distance(vector<int>& a, vector<int>& b) {
return pow(abs(1ll* (a[0]-b[0])),2) + pow(abs(1ll* (a[1]-b[1])),2);
}
bool inRange(vector<int>& a, vector<int>& b) {
return 1ll* a[2] * a[2] >= distance(a,b);
}
public:
int maximumDetonation(vector<vector<int>>& bombs) {
int res = 0, n = bombs.size();
sort(bombs.begin(), bombs.end(), []( const vector<int>& a, const vector<int>& b ){return a[2] < b[2];});
unordered_map<int, set<int>> m;
for(int i = 0; i < n; i++) {
queue<int> q;
set<int> s;
unordered_set<int> skip;
q.push(i);
s.insert(i);
while(!q.empty()) {
int pos = q.front();
q.pop();
if(skip.count(pos)) continue;
for(int np = 0; np < n; np++) {
if(s.count(np)) continue;
if(!inRange(bombs[pos], bombs[np])) continue;
if(m.count(np)) {
s.insert(m[np].begin(), m[np].end());
skip.insert(m[np].begin(), m[np].end());
} else {
s.insert(np);
q.push(np);
}
}
}
res = max(res, (int)s.size());
m[i] = s;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/28/PS/LeetCode/detonate-the-maximum-bombs/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.