gpt4 book ai didi

java - 使用 Dijkstra 检测多条最短路径

转载 作者:行者123 更新时间:2023-11-30 10:15:33 25 4
gpt4 key购买 nike

给定一个加权有向图,如何修改 Dijkstra 算法以测试给定节点对之间是否存在多条成本最低的路径?

我目前的算法如下:(归功于 Weiss)

/**
* Single-source weighted shortest-path algorithm. (Dijkstra)
* using priority queues based on the binary heap
*/
public void dijkstra( String startName )
{
PriorityQueue<Path> pq = new PriorityQueue<Path>( );

Vertex start = vertexMap.get( startName );
if( start == null )
throw new NoSuchElementException( "Start vertex not found" );

clearAll( );
pq.add( new Path( start, 0 ) ); start.dist = 0;

int nodesSeen = 0;
while( !pq.isEmpty( ) && nodesSeen < vertexMap.size( ) )
{
Path vrec = pq.remove( );
Vertex v = vrec.dest;
if( v.scratch != 0 ) // already processed v
continue;

v.scratch = 1;
nodesSeen++;

for( Edge e : v.adj )
{
Vertex w = e.dest;
double cvw = e.cost;

if( cvw < 0 )
throw new GraphException( "Graph has negative edges" );

if( w.dist > v.dist + cvw )
{
w.dist = v.dist +cvw;
w.prev = v;
pq.add( new Path( w, w.dist ) );
}
}
}
}

最佳答案

用集合prevs替换字段prev,指向前一个顶点的链接,并稍微更改代码:

...

if( w.dist >= v.dist + cvw ) {
if ( w.dist > v.dist + cvw ) {
w.dist = v.dist +cvw;
w.prevs.clear();
}
w.prevs.add(v);
pq.add( new Path( w, w.dist ) );
}

...

关于java - 使用 Dijkstra 检测多条最短路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50411987/

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