漫行记Wandering
Journal 1,371 字 5 分钟 Graph

Detonate the Maximum Bombs

Problem Description

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.

Problem Link

Solution 1: Graph + DFS

At first, i think it’s a typical Union-Find problem, but after thinking about it, Union-Find is not suitable for this problem, because the connection is directed, i.e., bomb A can detonate bomb B, but bomb B may not be able to detonate bomb A. Union-Find is used to solve undirected graph connectivity problems.

So we can use Graph + DFS to solve this problem.

Code


func maximumDetonation(bombs [][]int) int {
    n := len(bombs)

    graph := make([][]int, n)

    for i := 0; i < n; i++ {
        for j := 0; j < n; j++ {
            if i != j {
                dx := bombs[j][0] - bombs[i][0]
                dy := bombs[j][1] - bombs[i][1]
                dt := dx*dx + dy*dy
                radius := bombs[i][2] * bombs[i][2]
                if radius >= dt {
                    graph[i] = append(graph[i], j)
                }
            }
        }
    }

    maxBombs := 1

    for i := 0; i < n; i++ {
        visited := make([]bool, n)
        count := dfs(graph, i, visited)
        if count > maxBombs {
            maxBombs = count
        }
    }
    return maxBombs


}

func dfs(graph [][]int, bomb int, visited []bool) int {
    visited[bomb] = true
    count := 1

    for _, v := range graph[bomb] {
        if !visited[v] {
            count += dfs(graph, v, visited)
        }
    }
    return count
}

Time Complexity: O(n^3)

Space Complexity: O(n)

← 随笔