323. Number of Connected Components in an Undirected Graph

  寻找多少个独立的图,那不就是遍历完一个图,然后遍历其他图吗? 直到所有的点都遍历完。
  创建两个unordered_set, 一个记录访问过的,一个记录没有访问过的点。
  遍历每个图的节点的时候,动态的更新这两个set。

当第一个独立的图遍历完后 ret++;

如果记录没有访问过的点不为空,那么就继续循环去遍历。

这个办法可以,但是效率低。

class Solution {
public:
    unordered_map<int, vector<int>>  buildGraph(vector<vector<int>> edges) {
        unordered_map<int, vector<int>> graph;
        
        for(auto & edge: edges) {
            graph[edge[0]].push_back(edge[1]);
            graph[edge[1]].push_back(edge[0]);
        }
        return graph;
    }
    
    
    int countComponents(int n, vector<vector<int>>& edges) {
        //寻找多少个独立的图,那不就是遍历完一个图,然后遍历其他图吗? 直到所有的点都遍历完。
        //创建两个unordered_set, 一个记录访问过的,一个记录没有访问过的点。
        //遍历每个图的节点的时候,动态的更新这两个set。
        
        if(edges.size() == 0 && n == 1)
            return 1;
        else if(edges.size() == 0 && n == 0)
            return 0;
        
        int ret;
        
        queue<int> myqueue;
        unordered_set<int> accessedVertex, unAccessedVertex;
        
        for(int i=0;i<n;i++)
            unAccessedVertex.insert(i);
        
        unordered_map<int, vector<int>> neighbors = buildGraph(edges);
        
        while(unAccessedVertex.size()!=0) {
            int tmp = *unAccessedVertex.begin();
            myqueue.push(tmp);
            accessedVertex.insert(tmp);
            unAccessedVertex.erase(tmp);

            while(!myqueue.empty()) {
                int v = myqueue.front();
                myqueue.pop();

                for(auto &neighbor: neighbors[v]) {
                    if(accessedVertex.find(neighbor) != accessedVertex.end())
                        continue;
                    else
                    {       myqueue.push(neighbor);
                            accessedVertex.insert(neighbor);
                            unAccessedVertex.erase(neighbor);
                    }
                }
            }
            ret++;
        }
        
        return ret;
    }
};

应该还有更好的办法,先看看9章视频看看。

### Kruskal Algorithm Minimum Spanning Tree Implementation in C Language The Kruskal algorithm finds the minimum spanning tree (MST) from a given weighted graph. The MST connects all vertices within the graph through edges with minimal total weight. Below is an example of how one can implement the Kruskal's algorithm for finding the minimum spanning tree using C: ```c #include <stdio.h> #include <stdlib.h> // A structure to represent a weighted edge in graph struct Edge { int src, dest, weight; }; // A structure to represent a connected, undirected and weighted graph struct Graph { int V, E; struct Edge* edge; }; // Creates a graph with V vertices and E edges struct Graph* createGraph(int V, int E) { struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph)); graph->V = V; graph->E = E; graph->edge = (struct Edge*) malloc(graph->E * sizeof(struct Edge)); return graph; } // A utility function to find set of an element i (uses path compression technique) int find(int parent[], int i) { if (parent[i] == i) return i; return find(parent, parent[i]); } // A function that does union of two sets of x and y (uses union by rank) void Union(int parent[], int rank[], int x, int y) { int xroot = find(parent, x); int yroot = find(parent, y); // Attach smaller rank tree under root of high rank tree (Union by Rank) if (rank[xroot] < rank[yroot]) parent[xroot] = yroot; else if (rank[xroot] > rank[yroot]) parent[yroot] = xroot; // If ranks are same, then make one as root and increment its rank by one else { parent[yroot] = xroot; rank[xroot]++; } } // Compare two edges according to their weights. int myComp(const void* a, const void* b) { struct Edge* a1 = (struct Edge*)a; struct Edge* b1 = (struct Edge*)b; return a1->weight > b1->weight; } // The main function to construct MST using Kruskal's algorithm void KruskalMST(struct Graph* graph) { int V = graph->V; struct Edge result[V]; // This will store the resultant MST int e = 0; // An index variable, used for result[] int i = 0; // An index variable, used for sorted edges qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp); // Allocate memory for creating V subsets int *parent = (int *) malloc(V * sizeof(int)); int *rank = (int *) malloc(V * sizeof(int)); // Create V subsets with single elements for (int v = 0; v < V; ++v) { parent[v] = v; rank[v] = 0; } // Number of edges to be taken is equal to V-1 while (e < V - 1 && i < graph->E) { struct Edge next_edge = graph->edge[i++]; int x = find(parent, next_edge.src); int y = find(parent, next_edge.dest); // If including this edge doesn't cause cycle, include it in result and increment the index of result for next edge if (x != y) { result[e++] = next_edge; Union(parent, rank, x, y); } // Else discard the next_edge } printf("Following are the edges in the constructed MST\n"); for (i = 0; i < e; ++i) printf("%d -- %d == %d\n", result[i].src, result[i].dest, result[i].weight); return; } ``` This implementation uses disjoint-set data structures to efficiently manage merging components during execution[^4].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值