Statementâ–¼
You are given a list of bombs, where each bomb has a specific location and a range of effects. The range of a bomb is defined as a circular area centered at the bomb’s location, with a radius equal to the bomb’s range. If a bomb is detonated, it will trigger all other bombs whose centers lie within its range. These triggered bombs will further detonate any bombs within their respective ranges, creating a chain reaction.
The bombs are represented by a 0-indexed 2D integer array, bombs
, where:
bombs[i] = [xi, yi, ri]
:xi
andyi
represent the X and Y coordinates of the bomb’s location.ri
represents the radius of the bomb’s range.
You may choose to detonate one bomb initially. Your task is to determine the maximum number of bombs that can be detonated if you start with the optimal choice of the initial bomb.
Note: A bomb will be detonated even if its location lies exactly on the boundary of another bomb’s detonation radius.
Constraints:
1≤ bombs.length
Â≤100 bombs[i].length == 3
1≤xi​, yi​, ri​≤1000
Solution
This algorithm determines the maximum number of bombs that can be detonated in a chain reaction, given a list of bombs with their positions
The steps of the algorithm are as follows:
Create an adjacency list
graph
withn
empty lists, wheren
is the number of bombs.For each bomb
i, retrieve its coordinates(x1​​, y1​​) and blast radiusr1​ ​.
Compare it with every other bombj by calculating the squared distance betweeni andj .
Ifj lies within the blast radius ofi ((x2​​−x1​​)2+(y2​​−y1​​)2≤r12​​) , addj tograph[i]
.Implement a depth-first search (DFS) function that:
Adds the current bomb (node) to a
visited
set.Recursively visits all neighbors of the current node that haven’t been visited.
Returns the size of the
visited
set, representing the number of detonated bombs.
For each bomb,
i , perform a DFS starting fromi . Calculate the number of bombs detonated and updatemax_detonated
with the maximum value found.After iterating through all bombs, return
max_detonated
, which holds the largest chain reaction size.
Let’s look at the following illustration to get a better understanding of the solution: