gpt4 book ai didi

c# - 如何在 QuickGraph Dijkstra 或 A* 中设置目标顶点

转载 作者:行者123 更新时间:2023-11-30 15:41:12 27 4
gpt4 key购买 nike

我使用的是 QuickGraph 3.6 版,我找到了函数 SetRootVertex,但没有找到 SetTagretVertex。我需要这个,因为我正在巨大的图中搜索短路径,这会大大加快程序速度。

有问题的类是 DijkstraShortestPathAlgorithm 和 AStarShortestPathAlgorithm。

最佳答案

我不认为没有使用事件的方法。

您可以将必要的代码包装在一个扩展方法中,使事情变得清晰,例如:

public static class Extensions
{
class AStarWrapper<TVertex, TEdge>
where TEdge : IEdge<TVertex>
{
private TVertex target;
private AStarShortestPathAlgorithm<TVertex, TEdge> innerAlgorithm;
public AStarWrapper(AStarShortestPathAlgorithm<TVertex, TEdge> innerAlgo, TVertex root, TVertex target)
{
innerAlgorithm = innerAlgo;
this.innerAlgorithm.SetRootVertex(root);
this.target = target;
this.innerAlgorithm.FinishVertex += new VertexAction<TVertex>(innerAlgorithm_FinishVertex);
}
void innerAlgorithm_FinishVertex(TVertex vertex)
{
if (object.Equals(vertex, target))
this.innerAlgorithm.Abort();
}
public double Compute()
{
this.innerAlgorithm.Compute();
return this.innerAlgorithm.Distances[target];
}
}

public static double ComputeDistanceBetween<TVertex, TEdge>(this AStarShortestPathAlgorithm<TVertex, TEdge> algo, TVertex start, TVertex end)
where TEdge : IEdge<TVertex>
{
var wrap = new AStarWrapper<TVertex, TEdge>(algo, start, end);
return wrap.Compute();
}
}

用法:

var g = new BidirectionalGraph<int, IEdge<int>>();

g.AddVerticesAndEdge(new Edge<int>(1, 2));
g.AddVerticesAndEdge(new Edge<int>(2, 3));
g.AddVerticesAndEdge(new Edge<int>(3, 4));
g.AddVerticesAndEdge(new Edge<int>(2, 4));

var astar =new AStarShortestPathAlgorithm<int,IEdge<int>>(g, x => 1.0, x => 0.0);
var dist = astar.ComputeDistanceBetween(2, 4);

关于c# - 如何在 QuickGraph Dijkstra 或 A* 中设置目标顶点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8606494/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com