最小生成树
A minimum spanning tree of a weighted, connected graph is a subgraph in which a tree connects all the vertices together and has the minimum weight.
Prime's algorithm is a greedy algorithm that finds a minimum spanning tree for a undirected graph.
algorithm description
time complexity: O(|V|2)
Definition of Edge
class Edge{ int from; int to; int weight; Edge(int u,int v,int w){ from=u; to=v; weight=w; } }
Input - Weighted, connected Graph G, set v for vertices, set e for edges, starting vertex s Output - Minimum Spanning Tree Prims(G, v, e, s) { for i = 0 to v visited[i] = false visited[start] = true count = 0 // counts vertices visited int min = 9999 //to get minimum edge for (int i = 0; i < v; i++) { if(visited[i]) { for (int j = 0; j < v; j++) { if (edge between i and j exists and visited[j] is false) { if (min > G[i][j]) { min = G[i][j]; x = i; y = j; add edge to Minimum Spanning Tree } } } } }
algorithm description
time complexity: O(|E|log|E|)
MST- KRUSKAL (G, w) 1. A ← ∅ 2. for each vertex v ∈ V [G] 3. do MAKE - SET (v) 4. sort the edges of E into non decreasing order by weight w 5. for each edge (u, v) ∈ E, taken in non decreasing order by weight 6. do if FIND-SET (μ) ≠ if FIND-SET (v) 7. then A ← A ∪ {(u, v)} 8. UNION (u, v) 9. return A