Expm 4_1 多段图中的最短路径问题

 

【问题描述】

建立一个从源点S到终点T的多段图,设计一个动态规划算法求出从S到T的最短路径值,并输出相应的最短路径。

 解

 1 package org.xiu68.exp.exp4;
 2 
 3 public class Exp4_1 {
 4     //建立一个从源点S到终点T的多段图,设计一个动态规划算法求出从S到T的最短路径值,并输出相应的最短路径。
 5     /*
 6     d[1] = 0
 7     for j = 2 to n:
 8     for all <i,j>∈E :
 9     d[j] = min{ d[i] + wij }
10     return d[n]
11     */
12     public static void main(String[] args) {
13         // TODO Auto-generated method stub
14         int m=Integer.MAX_VALUE;
15         int[][] edges=new int[][]{
16             {m,1,2,5,m,m,m,m},
17             {m,m,m,m,4,11,m,m},
18             {m,m,m,m,9,5,16,m},
19             
20             {m,m,m,m,m,m,2,m},
21             {m,m,m,m,m,m,m,18},
22             {m,m,m,m,m,m,m,13},
23             
24             {m,m,m,m,m,m,m,2},
25             {m,m,m,m,m,m,m,m},
26         };
27         
28         MGraph graph1=new MGraph(edges);
29         graph1.minMultistageGraphPath(0, 7);
30         
31     }
32 
33 }
34 
35 class MGraph{
36     private int[][] edges;        //有向图表示多段图
37     private int vexNum;            //顶点数量
38     
39     public MGraph(int[][] edges){
40         this.edges=edges;
41         this.vexNum=edges.length;
42     }
43     
44     public void minMultistageGraphPath(int start,int end){
45         int[] dist=new int[vexNum];        //从源点到该点的路径长度
46         dist[start]=0;
47         
48         int[] pre=new int[vexNum];        //在最短路径中该点的前一个顶点
49         pre[start]=-1;
50         
51         for(int j=1;j<vexNum;j++){    
52             
53             dist[j]=Integer.MAX_VALUE;
54             pre[j]=-1;
55             
56             for(int i=0;i<vexNum;i++){
57                 if(edges[i][j]!=Integer.MAX_VALUE && dist[j]>dist[i]+edges[i][j]){
58                     dist[j]=dist[i]+edges[i][j];
59                     pre[j]=i;
60                 }
61             }
62         }
63         
64         
65         //打印最短路径
66         System.out.println(start+" to "+end+" is "+dist[end]);
67         
68         String path=""+end;
69         int preVex=pre[end];
70         
71         while(preVex!=-1){
72             path=preVex+"-->"+path;
73             preVex=pre[preVex];
74         }
75         System.out.println("the path is:"+path);
76     }
77 }
View Code
原文地址:https://www.cnblogs.com/xiu68/p/7988649.html