题目描述:
On a 2D plane, we place stones at some integer coordinate points. Each coordinate point may have at most one stone.
Now, a move consists of removing a stone that shares a column or row with another stone on the grid.
What is the largest possible number of moves we can make?
Example 1:
Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
Output: 5
Example 2:
Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
Output: 3
Example 3:
Input: stones = [[0,0]]
Output: 0
Note:
1. 1 <= stones.length <= 1000
2. 0 <= stones[i][j] < 10000
class Solution {
public:
int removeStones(vector<vector<int>>& stones) {
int n=stones.size();
if(n<=1) return 0;
for(int i=0;i<n;i++) parent[i]=i; //每个元素的初始化根节点都是自己
for(int i=0;i<n;i++)
{
for(int j=0;j<i;j++)
{
//发现横或纵坐标相同,将这两个元素的下标合并
if(stones[i][0]==stones[j][0]||stones[i][1]==stones[j][1])
uni(i,j);
}
}
int root_count=0;
for(auto x: parent) if(x.first==x.second) root_count++;
return n-root_count;
}
int find(int i)
{
if(parent[i]!=i) return find(parent[i]);
else return i;
}
void uni(int i, int j)
{
int x=find(i);
int y=find(j);
parent[x]=y; //合并的操作就是将一个根的根节点设为另一个根
}
private:
unordered_map<int,int> parent;
};