【发布时间】:2018-05-18 13:04:29
【问题描述】:
给定一个加权有向图,如何修改 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 ) );
}
}
}
}
【问题讨论】:
-
您只想检测多个等价路径(即返回一个布尔值),还是要列出所有等价路径?
-
@pkpnd 我只需要多个最短路径的布尔指标,而不是所有实际路径。
标签: java graph-theory shortest-path dijkstra