[Problem] Detonate the Maximum Bombs

댕청·2025년 10월 12일

문제 풀이

목록 보기
21/40

Problem Statement

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.

Example

Input: bombs = [[2,1,3],[6,1,4]]
Output: 2
Explanation: The above figure shows the positions and ranges of the 2 bombs. If we detonate the left bomb, the right bomb will not be affected. But if we detonate the right bomb, both bombs will be detonated. So the maximum bombs that can be detonated is max(1, 2) = 2.

Approach

As much as I prefer peace than analyzing the maximum amount of terror I can cause, I approached the problem through a BFS approach where each bomb is a node, and directed edges can be created based on the bombs' radius and distance.

For example, if the radius of one bomb is greater than its distance to another, popping it would also cause the other bomb to detonate. The problem then turns into a implicit graph problem.

Solution

def distance(x1, y1, x2, y2):
    return math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2)

class Solution:

    def maximumDetonation(self, bombs: List[List[int]]) -> int:
        nodes = defaultdict(set)

        for i in range(len(bombs)):
            for j in range(i, len(bombs)):
                
                radi = distance(bombs[i][0], bombs[i][1], bombs[j][0], bombs[j][1])

                if radi <= bombs[i][2]:
                    nodes[i].add(j)
                if radi <= bombs[j][2]:
                    nodes[j].add(i)

        visited = defaultdict(set)

        def dfs(curr, start):
            visited[start].add(curr)
            for node in nodes[curr]:
                if node not in visited[start]:
                    dfs(node, start)
        
        max_detonated = 0

        for i in range(len(bombs)): 
            dfs(i, i)
            max_detonated = max(max_detonated, len(visited[i]))

        return max_detonated
            `
profile
될때까지 모든 걸 다시 한번

0개의 댓글