import java.util.Scanner; import java.util.Stack; public class Test2_5 { static int n; //Number of cities static int m; //Number of routes between cities static int N=100; //The number of cities, can be modified static int INF=1000000; //initialize infinity static int[][] map=new int[N][N]; static int[] dist=new int[N]; static int[] p=new int[N]; static boolean[] flag=new boolean[N]; static void Dijkstra(int u) { for (int i=1;i<=n;i++) { dist[i]=map[u][i]; flag[i]=false; if (dist[i]==INF) p[i]=-1; else p[i]=u; } dist[u]=0; flag[u]=true; for (int i=1;i<=n;i++) { int temp = INF, t = u; for (int j=1;j<=n;j++) if (!flag[j]&&dist[j]<temp) { t=j; temp=dist[j]; } if (t==u) return; flag[t]=true; for (int j=1;j<=n;j++) { if (!flag[j]&&map[t][j]<INF) if (dist[j]>(dist[t]+map[t][j])) { dist[j]=dist[t]+map[t][j]; p[j]=t; } } } } static void findpath(int u) { int x; Stack<Integer> s=new Stack<Integer>(); System.out.println("The source point is: "+u); for (int i=1;i<=n;i++) { x=p[i]; while (x!=-1) { s.push(x); x=p[x]; } System.out.print("The shortest path from the source point to other vertices is: "); while (!s.empty()) { System.out.print(s.peek()+"--"); s.pop(); } System.out.println(i+"; The shortest distance is: "+dist[i]); } } public static void main(String[] args) { // TODO Auto-generated method stub int u,v,w,st; Scanner sc = new Scanner(System.in); System.out.println("Please enter the number of cities: "); n = sc.nextInt(); System.out.println("Please enter the number of routes between cities: "); m = sc.nextInt(); System.out.println("Please enter the route and distance between cities: "); for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) { map[i][j]=INF; } while (m--!=0) { u=sc.nextInt(); v=sc.nextInt(); w=sc.nextInt(); map[u][v]=Math.min(map[u][v], w); } System.out.println("Please enter Xiaoming's location: "); st=sc.nextInt(); Dijkstra(st); System.out.println("Xiao Ming's location: "+st); for (int i=1;i<=n;i++) { System.out.print("Xiao Ming: "+st+" - where "+" is going: "+i); if(dist[i]==INF) System.out.println("sorry, no way to reach"); else System.out.println("The shortest distance is: "+dist[i]); } findpath(st); } }
Chapter 2-5 A Journey That Said to Go---The Shortest Path
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=324691360&siteId=291194637
Recommended
Ranking