给定一个加权有向图,如何修改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 ) );
}
}
}
}发布于 2018-05-18 21:22:48
如果您只想找到一条其他等价路径
假设您已经运行了一次Dijkstra算法来获得最短路径P。您可以在P中的每条边添加一个微小的成本epsilon,并在修改后的图上第二次运行Dijkstra's,以获得新的路径P'。如果P和P'包含相同的边,则可以得出P是唯一最短路径的结论。否则,我们撤消epsilon更改并比较P和P'的长度。如果长度相等,那么显然P'是另一条截然不同的最短路径。否则,P是唯一的最短路径。
如果我们想找出所有最短路径
这样的算法必然是指数时间的。这是因为一个图在两个节点之间可以有指数级的多条等价路径。例如,考虑下面的图:
A --> B1 --> C --> D1 --> E ...
\ -> \ ->
-> B2 / -> D2 /从A到E有4条路径,如果我们假设所有边的成本相等,那么所有这些路径的总成本都相等。通过重复这个模式,我们可以得到成倍增长的相等成本的路径。
发布于 2018-05-18 21:38:11
将前一个顶点的链接字段prev替换为集合prevs,并稍微修改代码:
...
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 ) );
}
...https://stackoverflow.com/questions/50411987
复制相似问题