Approach
Depth-first search
For Most Stones Removed with Same Row or Column, 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
- 32 lines of Java from the credited upstream file 947.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 5 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 removeStones(int[][] stones) {3 int numOfIslands = 0;4 List<Integer>[] graph = new List[stones.length];5 Set<Integer> seen = new HashSet<>();6 7 for (int i = 0; i < graph.length; ++i)8 graph[i] = new ArrayList<>();9 10 for (int i = 0; i < stones.length; ++i)11 for (int j = i + 1; j < stones.length; ++j)12 if (stones[i][0] == stones[j][0] || stones[i][1] == stones[j][1]) {13 graph[i].add(j);14 graph[j].add(i);15 }16 17 for (int i = 0; i < stones.length; ++i)18 if (seen.add(i)) {19 dfs(graph, i, seen);20 ++numOfIslands;21 }22 23 return stones.length - numOfIslands;24 }25 26 private void dfs(List<Integer>[] graph, int u, Set<Integer> seen) {27 for (final int v : graph[u])28 if (seen.add(v))29 dfs(graph, v, seen);30 }31}32