介绍
最小生成树概念与算法介绍
QuikGraph的PrimMinimumSpanningTreeAlgorithm的API地址
示例
测试代码:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using QuikGraph;
using QuikGraph.Algorithms.MinimumSpanningTree;
using QuikGraph.Algorithms.Observers;
using System;
using System.Collections.Generic;
namespace QuikGraphTest
{
[TestClass]
public class TestPrim
{
UndirectedGraph<string, EquatableEdge<string>> _graph
= new UndirectedGraph<string, EquatableEdge<string>>();
private readonly Dictionary<EquatableEdge<string>, double> _weightsDict
= new Dictionary<EquatableEdge<string>, double>();
private void AddVertex(string v)
{
_graph.AddVertex(v);
}
private void AddEdge(string from, string to, double weight = 1)
{
var e1 = new EquatableEdge<string>(from, to);
var e2 = new EquatableEdge<string>(to, from);
_graph.AddEdge(e1);
_graph.AddEdge(e2);
_weightsDict.Add(e1, weight);
_weightsDict.Add(e2, weight);
}
public Func<EquatableEdge<string>, double> GetWeightsFunc()
{
return edge => _weightsDict[edge];
}
[TestMethod]
public void TestMethod1()
{
AddVertex("n1");
AddVertex("n2");
AddVertex("n3");
AddVertex("n4");
AddVertex("n5");
AddVertex("n6");
AddEdge("n1", "n2", 10);
AddEdge("n2", "n3", 8);
AddEdge("n3", "n4", 11);
AddEdge("n4", "n5", 6);
AddEdge("n5", "n6", 9);
AddEdge("n1", "n6", 3);
AddEdge("n2", "n6", 5);
AddEdge("n3", "n6", 18);
AddEdge("n3", "n5", 21);
var prim = new PrimMinimumSpanningTreeAlgorithm<string, EquatableEdge<string>>
(_graph, GetWeightsFunc());
var edgeRecorder = new EdgeRecorderObserver<string, EquatableEdge<string>>();
using (edgeRecorder.Attach(prim))
prim.Compute();
foreach (var edge in edgeRecorder.Edges)
{
Console.WriteLine(edge);
}
}
}
}
控制台输出:
n1 -> n6
n2 -> n6
n2 -> n3
n5 -> n6
n4 -> n5
效果图: