Detonate the Maximum Bombs

Build edge i to j iff bomb i reaches bomb j; BFS/DFS from each source and take the max reachable.

Medium
Time O(n^2 + n * (n + e)) Space O(n^2)
LeetCode
5 min read
geometry graph bfs dfs

Problem#

Each bomb has a 2D position and radius. Detonating one triggers others within its radius, which trigger their own neighbors. Pick a starting bomb to maximize the total detonated.

Examples#

  • [[2,1,3],[6,1,4]]2.
  • [[1,1,5],[10,10,5]]1.

Constraints#

  • 1 <= bombs.length <= 100.

Approach#

Build a directed graph: edge i → j iff bomb j lies inside bomb i’s radius (squared distance test). BFS/DFS from each bomb to count reachable; return the max.

Solution#

Detonate the Maximum Bombs
class Solution {
public:
int maximumDetonation(vector<vector<int>>& bombs) {
int n = bombs.size();
vector<vector<int>> adj(n);
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j) if (i != j) {
long long dx = bombs[i][0] - bombs[j][0];
long long dy = bombs[i][1] - bombs[j][1];
long long r = bombs[i][2];
if (dx * dx + dy * dy <= r * r) adj[i].push_back(j);
}
int best = 0;
for (int s = 0; s < n; ++s) {
vector<int> vis(n, 0);
vis[s] = 1;
queue<int> q;
q.push(s);
int cnt = 0;
while (!q.empty()) {
int u = q.front(); q.pop();
++cnt;
for (int v : adj[u]) if (!vis[v]) { vis[v] = 1; q.push(v); }
}
best = max(best, cnt);
}
return best;
}
};

Editorial#

The relation “i triggers j” is directed because bomb radii differ — i may cover j without j covering i. Squared-distance comparison avoids floats. Trying every starting bomb is O(n) BFSes, each O(n + edges) — well within the n <= 100 budget.

Complexity#

  • Time: O(n^2) graph build + O(n * (n + e)) BFS.
  • Space: O(n^2).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.