#2101
Detonate the Maximum Bombs
MediumArrayMathDepth-First SearchBreadth-First SearchGraph TheoryGeometryGraph TheoryDepth-First SearchAdjacency List
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
We can model the bombs as a directed graph where each bomb is a node and an edge exists from bomb A to bomb B if A can detonate B. We can use Depth-First Search (DFS) to explore this graph efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Create an adjacency list to represent the graph of bombs based on their ranges.
- 2Step 2: For each bomb, perform a DFS to count how many bombs can be detonated starting from that bomb.
- 3Step 3: Track the maximum count of detonated bombs across all DFS calls.
solution.py29 lines
1# Full working Python code
2from math import sqrt
3from collections import defaultdict
4
5def detonateMaximumBombs(bombs):
6 n = len(bombs)
7 graph = defaultdict(list)
8
9 # Build the graph
10 for i in range(n):
11 for j in range(n):
12 if i != j and in_range(bombs[i], bombs[j]):
13 graph[i].append(j)
14
15 def in_range(b1, b2):
16 return sqrt((b1[0] - b2[0])**2 + (b1[1] - b2[1])**2) <= b1[2]
17
18 def dfs(bomb_index, visited):
19 count = 1 # Current bomb is counted
20 visited.add(bomb_index)
21 for neighbor in graph[bomb_index]:
22 if neighbor not in visited:
23 count += dfs(neighbor, visited)
24 return count
25
26 max_bombs = 0
27 for i in range(n):
28 max_bombs = max(max_bombs, dfs(i, set()))
29 return max_bombsℹ
Complexity note: The time complexity remains O(n²) due to the nested loop for building the graph. However, the space complexity is O(n) because we are storing the adjacency list for the graph.
- 1Modeling the problem as a graph helps in understanding the relationships between bombs.
- 2Using DFS allows us to efficiently explore all possible detonations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.