int findCircleNum(vector<vector<int>>& M)
{
int n=M.size();
vector<int> parents(n,0);
for(int i=0;i<n;++i)
{
parents[i]=i;
}
function<int(int,vector<int>&)>finds=[&finds](int x,vector<int> &parents)->int{return parents[x]==x?x:parents[x]=finds(parents[x],parents);};
int cnt=n;
for(int i=0;i<n;++i)
{
for(int j=i+1;j<n;++j)
{
if(M[i][j]==1)
{
int ip=finds(i,parents);
int jp=finds(j,parents);
if(ip!=jp)parents[ip]=jp,cnt--;
}
}
}
return cnt;
}
[LeetCode] 547. Friend Circles
最新推荐文章于 2022-05-19 20:41:15 发布