最短路径问题 java
1 import java.util.Scanner; 2 3 public class Shortway{ 4 int[][] e=new int[7][7]; 5 int[][] a={{0,0,0},{1,2,1},{2,4,2},{3,2,2},{4,5,3},{3,6,1},{1,3,3}}; 6 int inf=99999; 7 int[] book=new int[7]; 8 int[] con=new int[7]; 9 public static void main(String args[]){ 10 Shortway s=new Shortway(); 11 s.go(); 12 } 13 public void go(){ 14 scannin(); 15 int u; 16 17 for(int i=1;i<=6;i++){ 18 book[i]=1; 19 } 20 for(int i=1;i<=6;i++){ 21 con[i]=e[1][i]; 22 } 23 for(int i=1;i<=6;i++){ 24 System.out.print(con[i]); 25 } 26 for(int n=1;n<=5;n++){ 27 int j=1; 28 int temp=inf; 29 for(int i=1;i<=6;i++){ 30 if(book[i]!=0&&con[i]<temp){ 31 temp=con[i]; 32 j=i; 33 } 34 } 35 u=j; 36 System.out.println(u); 37 book[u]=0; 38 for(int i=1;i<=6;i++){ 39 if(book[i]!=0&&con[i]>con[u]+e[u][i]){ 40 con[i]=con[u]+e[u][i]; 41 } 42 } 43 } 44 45 for(int i=1;i<=6;i++){ 46 System.out.println(con[i]); 47 } 48 } 49 public void scannin(){ 50 /* for(int i=1;i<=6;i++){ 51 for(int j=1;j<=3;j++){ 52 Scanner scanner = new Scanner(System.in); 53 a[i][j]=scanner.nextInt(); 54 } 55 } */ 56 for(int i=1;i<=6;i++){ 57 e[a[i][0]][a[i][1]]=a[i][2]; 58 } 59 for(int i=1;i<=6;i++){ 60 for(int j=1;j<=6;j++){ 61 if (i==j){ 62 e[i][j]=0; 63 }else if(e[i][j]==0){ 64 e[i][j]=inf; 65 } 66 } 67 } 68 69 } 70 }