KatInterview

Largest Chain Reaction From a Single Detonation

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphsgraphdfsreachability

Last updated

Model one-way blast reach as a directed graph and find the largest set reachable from any single starting node, using exact integer distance checks.

Largest Chain Reaction From a Single Detonation

You are given a collection of explosive devices placed on a flat 2D grid. Each device is described by three integers [x, y, r]: its center is at (x, y) and its blast reaches every point within distance r of that center.

When a device goes off, it sets off every other device whose center lies within or exactly on the edge of its blast circle. In other words, device i sets off device j when the distance between their centers is at most r_i. Devices that are set off explode in turn, and may set off further devices, and so on until nothing new explodes.

You get to choose exactly one device to detonate by hand. Return the largest possible total number of devices that explode (including the one you chose) over all choices of starting device.

Details

  • The relation is one-directional. Device i reaching device j says nothing about whether j reaches i, because only the radius of the exploding device matters.
  • Only the radius of the device that is exploding is used when deciding whom it sets off.
  • Devices may share the same coordinates. They are different devices, and each one can set off the other if the distance (0) is within the exploding device's radius.
  • A radius of 0 means the device only sets off devices located at exactly the same coordinates.
  • If the list is empty, return 0.
  • Compare distances exactly, using integer arithmetic on squared values, to avoid floating-point error.

Input

  • bombs: a list of [x, y, r] integer triples.

Output

  • An integer: the maximum number of devices that can explode from a single manual detonation.

Constraints

  • 0 <= len(bombs) <= 100
  • Each entry is a list of three integers [x, y, r]
  • r >= 0
  • Coordinates and radii are integers whose squares fit comfortably in standard integer arithmetic (up to about 10^5 in magnitude)

Examples

Example 1

Input: max_chain_explosion([[0, 0, 2], [2, 0, 2], [5, 0, 1]])

Output: 2

Example 2

Input: max_chain_explosion([[0, 0, 10], [10, 0, 1]])

Output: 2

Hints

Hint 1

Think about who can trigger whom: if a big device covers a small one, does the small one necessarily cover the big one? Choose a graph representation that respects this.

Hint 2

Compare squared distance dx*dx + dy*dy against r*r using integers, so no square roots or floats are needed.

Hint 3

For each possible starting device, run a DFS or BFS over the directed graph and count visited devices; the answer is the maximum count.