LeetCode547朋友圈,使用并查集和图的搜索
1、使用并查集
class DisjoinSet{ private: vector<int>_id; //元素对应的集合,根 vector<int>_size; //集合大小 int _count; //集合个数 public: DisjoinSet(int n){ //初始化成n个集合 for(int i = 0;i < n;i++){ _id.push_back(i); _size.push_back(1); } _count = n; } //查 int _find(int p){ while(p!=_id[p]){ _id[p] = _id[_id[p]]; p = _id[p]; } return p; } //并,小规模向大规模上合并,提高查询效率 void _union(int p,int q){ int i = _find(p); int j = _find(q); if(i == j) return; if(_size[i]<_size[j]){ _id[i] = j; _size[j] += _size[i]; } else{ _id[j] = i; _size[i] += _size[j]; } _count--; } int count(){ return _count; } }; class Solution { public: int findCircleNum(vector<vector<int>>& M) { DisjoinSet ds(M.size()); for(int i = 0;i<M.size();i++) { for(int j = i+1;j<M.size();j++) if(M[i][j]) ds._union(i,j); } return ds.count(); } };
2、深度优先搜索图
void DFS_circle(int n,vector<vector<int>>& graph,vector<int>& visit) { visit[n] = 1; for(int i = 0;i<graph[n].size();i++) if(visit[i] == 0 && graph[n][i] == 1) DFS_circle(i,graph,visit); } //朋友圈 int findCircleNum(std::vector<std::vector<int>>& M) { //图的搜索 vector<int>visit(M.size(),0); int count = 0; for(int i = 0;i<M.size();i++) { if(visit[i]==0) { DFS_circle(i,M,visit); count++; } } return count; }