C#语言实现最小生成树算法(Minimum Spanning Tree)
最小生成树(Minimum Spanning Tree,MST)算法有多种实现方法,其中最常见的两种是Prim算法和Kruskal算法。以下是使用C#语言分别实现这两种算法的示例代码:
使用Prim算法实现最小生成树
Prim算法适用于稠密图(dense graph),它从一个顶点开始,逐步扩展最小生成树,直到包含所有顶点。
using System;
using System.Collections.Generic;
class PrimMST
{
private static int V = 5; // Number of vertices
// A utility function to find the vertex with minimum key value, from
// the set of vertices not yet included in MST
int MinKey(int[] key, bool[] mstSet)
{
// Initialize min value
int min = int.MaxValue, minIndex = -1;
for (int v = 0; v < V; v++)
if (mstSet[v] == false && key[v] < min)
{
min = key[v];
minIndex = v;
}
return minIndex;
}
// Function to print the constructed MST stored in parent[]
void PrintMST(int[] parent, int[,] graph)
{
Console.WriteLine("Edge \tWeight");
for (int i = 1; i < V; i++)
Console.WriteLine($"{parent[i]} - {i}\t{graph[i, parent[i]]}");
}
// Function to construct and print MST for a graph represented using adjacency matrix representation
public void PrimMST(int[,] graph)
{
int[] parent = new int[V]; // Array to store constructed MST
int[] key = new int[V]; // Key values used to pick minimum weight edge in cut
bool[] mstSet = new bool[V]; // To represent set of vertices not yet included in MST
// Initialize all keys as INFINITE
for (int i = 0; i < V; i++)
{
key[i] = int.MaxValue;
mstSet[i] = false;
}
// Always include first 1st vertex in MST.
key[0] = 0; // Make key 0 so that this vertex is picked as first vertex
parent[0] = -1; // First node is always root of MST
// The MST will have V vertices
for (int count = 0; count < V - 1; count++)
{
// Pick the minimum key vertex from the set of vertices not yet included in MST
int u = MinKey(key, mstSet);
// Add the picked vertex to the MST Set
mstSet[u] = true;
// Update key value and parent index of the adjacent vertices of the picked vertex.
// Consider only those vertices which are not yet included in MST
for (int v = 0; v < V; v++)
if (graph[u, v] != 0 && mstSet[v] == false && graph[u, v] < key[v])
{
parent[v] = u;
key[v] = graph[u, v];
}
}
// print the constructed MST
PrintMST(parent, graph);
}
// Driver Code
public static void Main()
{
/* Let us create the following graph
2 3
(0)--(1)--(2)
| / \ |
6| 8/ \5 |7
| / \ |
(3)-------(4)
9 */
int[,] graph = new int[,] {
{ 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 }
};
PrimMST t = new PrimMST();
t.PrimMST(graph);
}
}