using System;
using System.Collections.Generic;
using System.Linq;
namespace Prim算法
{
///
/// 顶点
///
public class Vertex
{
public String key;
public Vertex(String key)
{
this.key = key;
}
}
///
/// 边
///
public class Edge
{
public Vertex start;
public Vertex end;
public int key;
public Edge(Vertex start, Vertex end, int key)
{
this.start = start;
this.end = end;
this.key = key;
}
}
public class Prim
{
public static List vertexList = new List();//结点集
public static List EdgeQueue = new List();//边集
public static List newVertex = new List();//已经 访问过的结点
public static void buildGraph()
{
Vertex v1 = new Vertex("a");
Prim.vertexList.Add(v1);
Vertex v2 = new Vertex("b");
Prim.vertexList.Add(v2);
Vertex v3 = new Vertex("c");
Prim.vertexList.Add(v3);
Vertex v4 = new Vertex("d");
Prim.vertexList.Add(v4);
Vertex v5 = new Vertex("e");
Prim.vertexList.Add(v5);
addEdge(v1, v2, 6);
addEdge(v1, v3, 7);
addEdge(v2, v3, 8);
addEdge(v2, v5, 4);
addEdge(v2, v4, 5);
addEdge(v3, v4, 3);
addEdge(v3, v5, 9);
addEdge(v5, v4, 7);
addEdge(v5, v1, 2);
//addEdge(v4, v2, 2);
}
public static void addEdge(Vertex a, Vertex b, int w)
{
Edge e = new Edge(a, b, w);
Prim.EdgeQueue.Add(e);
}
public static void primTree()
{
buildGraph();
Vertex start = vertexList.ElementAt(0);
newVertex.Add(start);
for (int n = 0; n < vertexList.Count; n++)
{
Vertex temp = new Vertex(start.key);
Edge tempedge = new Edge(start, start, 1000);
foreach (Vertex v in newVertex)
{
foreach (Edge e in EdgeQueue)
{
if (e.start == v && !containVertex(e.end))
{
if (e.key < tempedge.key)
{
temp = e.end;
tempedge = e;
}
}
}
}
if (!containVertex(temp))
{
newVertex.Add(temp);
}
}
foreach (Vertex item in newVertex)
{
Console.WriteLine(item.key);
}
}
public static bool containVertex(Vertex vte)
{
foreach (Vertex v in newVertex)
{
if (v.key.Equals(vte.key))
return true;
}
return false;
}
public static void Main(String[] args)
{
primTree();
}
}
}