Java 我正在学习数据结构,遇到了Dijkstra';获取从一个节点(源)到另一个节点(目标)的最短路径的s算法
我遇到了一个问题,要求我查找从源节点到目标节点的最短路径,以及从目标节点返回到源节点的最短路径 printPath方法通过使用递归回溯到起始节点,然后回溯到最后一个节点,输出从源到目标的最短路径 打印路径方法:Java 我正在学习数据结构,遇到了Dijkstra';获取从一个节点(源)到另一个节点(目标)的最短路径的s算法,java,data-structures,graph,dijkstra,Java,Data Structures,Graph,Dijkstra,我遇到了一个问题,要求我查找从源节点到目标节点的最短路径,以及从目标节点返回到源节点的最短路径 printPath方法通过使用递归回溯到起始节点,然后回溯到最后一个节点,输出从源到目标的最短路径 打印路径方法: /** * Driver routine to handle unreachables and print total cost. * It calls recursive routine to print shortest path to * destNode after a s
/**
* Driver routine to handle unreachables and print total cost.
* It calls recursive routine to print shortest path to
* destNode after a shortest path algorithm has run.
*/
public void printPath( String destName )
{
Vertex w = vertexMap.get( destName );
if( w == null )
throw new NoSuchElementException( "Destination vertex not found" );
else if( w.dist == INFINITY )
System.out.println( destName + " is unreachable" );
else
{
System.out.print( "(Cost is: " + w.dist + ") " );
printPath( w );
System.out.println( );
}
}
/**
* Recursive routine to print shortest path to dest
* after running shortest path algorithm. The path
* is known to exist.
*/
private void printPath( Vertex dest )
{
String val;
if( dest.prev != null )
{
printPath( dest.prev );
// System.out.print( " to " );
System.out.print(' ');
}
System.out.print( dest.name );
}
Dijkstra的代码
/**
* 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 ) );
}
}
}
}
在我的主要方法中,当我运行时:
dijkstra("B")
printPath("D")
我得到这个输出:
(Cost is: 54.0) B E D
但是,由于我需要找到返回源的最短路径,因此需要的输出是:
(Cost is: 72.0) B E D C B
我应该在dijkstra的代码或printPath方法中修改什么以获得所需的输出?根据您的示例,我理解您希望图形被定向(即,它们只能单向遍历)。在这种情况下,您无法根据从起点开始的Dijkstra树找到从目的地返回起点的最短路径。或者从目的地开始第二次Dijkstra运行,或者从源开始第二次Dijkstra运行,边缘反转(第一个选项会更容易)。根据您的示例,我理解您希望图形被定向(即,它们只能以一种方式进行遍历)。在这种情况下,您无法根据从起点开始的Dijkstra树找到从目的地返回起点的最短路径。或者从目的地开始第二次Dijkstra运行,或者从源开始第二次Dijkstra运行,边缘反转(第一个选项更容易)。
(Cost is: 72.0) B E D C B