|
| 1 | +// 2101. Detonate the Maximum Bombs |
| 2 | +// 🟠 Medium |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/detonate-the-maximum-bombs/ |
| 5 | +// |
| 6 | +// Tags: Array - Math - Depth-First Search - Breadth-First Search - Graph - Geometry |
| 7 | + |
| 8 | +struct Solution {} |
| 9 | +impl Solution { |
| 10 | + /// The bombs form a directed graph where they are the nodes and the edges |
| 11 | + /// are formed between them and any other bombs that are within the radius |
| 12 | + /// of their explosions and will be triggered in a chain reaction. We can |
| 13 | + /// start by constructing an adjacency list using O(n^2) then we can do a |
| 14 | + /// graph traversal starting at each node checking how many bombs will be |
| 15 | + /// triggered and return the maximum result. |
| 16 | + /// |
| 17 | + /// Time complexity: O(n^3) - We perform a DFS that could have a time |
| 18 | + /// complexity of O(n^2) for each node in the graph. |
| 19 | + /// Space complexity: O(n^2) - The adjacency 2D vector. |
| 20 | + /// |
| 21 | + /// Runtime 18 ms Beats 100% |
| 22 | + /// Memory 2.2 MB Beats 100% |
| 23 | + pub fn maximum_detonation(bombs: Vec<Vec<i32>>) -> i32 { |
| 24 | + let n = bombs.len(); |
| 25 | + let mut res = 0; |
| 26 | + // Create an adjacency vector. |
| 27 | + let mut adj: Vec<Vec<usize>> = vec![vec![]; n]; |
| 28 | + // Iterate over all pairs. |
| 29 | + for i in 0..n { |
| 30 | + let (x1, y1, r1) = (bombs[i][0], bombs[i][1], bombs[i][2]); |
| 31 | + for j in i + 1..n { |
| 32 | + let (x2, y2, r2) = (bombs[j][0], bombs[j][1], bombs[j][2]); |
| 33 | + let dist = i64::pow((x1 - x2) as i64, 2) + i64::pow((y1 - y2) as i64, 2); |
| 34 | + if dist <= i64::pow(r1 as i64, 2) { |
| 35 | + // We can reach 2 from 1. |
| 36 | + adj[i].push(j); |
| 37 | + } |
| 38 | + if dist <= i64::pow(r2 as i64, 2) { |
| 39 | + adj[j].push(i); |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + fn dfs(i: usize, in_path: &mut Vec<bool>, adj: &Vec<Vec<usize>>) -> i32 { |
| 44 | + let mut count = 1; |
| 45 | + for nei in adj[i].iter() { |
| 46 | + let nei = *nei; |
| 47 | + if !in_path[nei] { |
| 48 | + in_path[nei] = true; |
| 49 | + count += dfs(nei, in_path, adj); |
| 50 | + } |
| 51 | + } |
| 52 | + count |
| 53 | + } |
| 54 | + let mut dp = vec![-1; n]; |
| 55 | + // Pick start nodes to do a |
| 56 | + for i in 0..n { |
| 57 | + let mut in_path = vec![false; n]; |
| 58 | + in_path[i] = true; |
| 59 | + dp[i] = dfs(i, &mut in_path, &adj); |
| 60 | + if dp[i] > res { |
| 61 | + res = dp[i]; |
| 62 | + } |
| 63 | + } |
| 64 | + res |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +fn main() { |
| 69 | + let tests = [ |
| 70 | + (vec![vec![2, 1, 3], vec![6, 1, 4]], 2), |
| 71 | + (vec![vec![1, 1, 5], vec![10, 10, 5]], 1), |
| 72 | + ]; |
| 73 | + for t in tests { |
| 74 | + assert_eq!(Solution::maximum_detonation(t.0), t.1); |
| 75 | + } |
| 76 | + println!("\x1b[92m» All tests passed!\x1b[0m") |
| 77 | +} |
0 commit comments