On a 2D plane, we place stones at some integer coordinate points. Each coordinate point may have at most one stone.spa
Now, a move consists of removing a stone that shares a column or row with another stone on the grid.code
What is the largest possible number of moves we can make?blog
Example 1:rem
Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
Output: 5
Example 2:input
Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
Output: 3
Example 3:it
Input: stones = [[0,0]] Output: 0
class Solution { private int[] p; public int removeStones(int[][] stones) { if(stones == null || stones.length <= 1) return 0; int n = stones.length; p = new int[n]; for(int i = 0; i < n; i++) p[i] = -1; for(int i = 0; i < n; i++){ for(int j = i + 1; j < n; j++){ if(stones[i][0] == stones[j][0] || stones[i][1] == stones[j][1]){ union(i, j); } } } for(int e : p){ if(e == -1){ n--; } } return n; } private void union(int i, int j){ int rooti = find(i); int rootj = find(j); if(rooti != rootj){ p[rooti] = rootj; } } private int find(int i){ while(p[i] != -1){ i = p[i]; } return i; } }