Approach
Depth-first search
For Detonate the Maximum Bombs, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 40 lines of Java from the credited upstream file 2101.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 4 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int maximumDetonation(int[][] bombs) {3 final int n = bombs.length;4 int ans = 0;5 List<Integer>[] graph = new List[n];6 Arrays.setAll(graph, i -> new ArrayList<>());7 8 for (int i = 0; i < n; ++i) {9 for (int j = 0; j < n; ++j) {10 if (i == j)11 continue;12 final long ri = bombs[i][2];13 if (ri * ri >= squaredDist(bombs, i, j))14 graph[i].add(j);15 }16 }17 18 for (int i = 0; i < n; ++i) {19 Set<Integer> seen = new HashSet<>(Arrays.asList(i));20 dfs(graph, i, seen);21 ans = Math.max(ans, seen.size());22 }23 24 return ans;25 }26 27 private void dfs(List<Integer>[] graph, int u, Set<Integer> seen) {28 for (final int v : graph[u]) {29 if (seen.contains(v))30 continue;31 seen.add(v);32 dfs(graph, v, seen);33 }34 }35 private long squaredDist(int[][] bombs, int i, int j) {36 return (long) (bombs[i][0] - bombs[j][0]) * (bombs[i][0] - bombs[j][0]) +37 (long) (bombs[i][1] - bombs[j][1]) * (bombs[i][1] - bombs[j][1]);38 };39}40