1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
| #include <iostream> #include <iomanip> using namespace std; #define SIZE 7 #define NUMBER 6 #define INFINITE 123456
int Graph_Matrix[SIZE][SIZE]; int Distance[SIZE];
void Create_Graph(int *Path_Cost) { int i,j; for(i=0;i<SIZE;i++) { for(j=0;j<SIZE;j++) { if(i==j) { Graph_Matrix[i][j]=0; } else { Graph_Matrix[i][j]=INFINITE; } } } int End_Point,Start_Point; i=0; while(i<SIZE) { Start_Point=Path_Cost[i*3]; End_Point=Path_Cost[i*3+1]; Graph_Matrix[Start_Point][End_Point]=Path_Cost[i*3+2]; i++; } }
void Print_Matrix() { int i=0,j=0; for(i=1;i<SIZE;i++) { cout << "vex" << i ; for(j=1;j<SIZE;j++) { if(Graph_Matrix[i][j]==INFINITE) { cout << setw(5) << "x"; } else { cout << setw(5) << Graph_Matrix[i][j]; } } cout << endl; } }
void Shortest_Path(int vertex1,int vertex_total) { int Shortest_vertex=1; int Shortest_distance; int flag[SIZE]; int i,j; for(i=1;i<=vertex_total;i++) { flag[i]=0; Distance[i]=Graph_Matrix[vertex1][i]; } flag[vertex1]=1; Distance[vertex1]=0; for(i=0;i<=vertex_total-1;i++) { Shortest_distance=INFINITE; for(j=0;j<=vertex_total;j++) { if(flag[j]==0 && Distance[j]<=Shortest_distance) { Shortest_distance=Distance[j]; Shortest_vertex=j; } } flag[Shortest_vertex]=1; for(j=0;j<=vertex_total;j++) { if(flag[j]==0 && Distance[Shortest_vertex]+Graph_Matrix[Shortest_vertex][j] <Distance[j]) { Distance[j]=Distance[Shortest_vertex]+Graph_Matrix[Shortest_vertex][j]; } } } } int main() { int Path_Cost[9][3]={{1,2,3},{1,3,5},{1,4,1},{1,5,3},{1,6,4}, {2,5,3},{4,5,7},{4,6,6},{4,3,2}}; cout << "=========================================" << endl; cout << "此范例图的邻接矩阵如下:" << endl; cout << "=========================================" << endl; cout << "顶点 vex1 vex2 vex3 vex4 vex5 vex6" << endl; Create_Graph(&Path_Cost[0][0]); Print_Matrix(); cout << "=========================================" << endl; cout << "顶点1到各顶点最短距离的最终结果" << endl; cout << "=========================================" << endl; Shortest_Path(1,NUMBER); for(int i=1;i<SIZE;i++) { cout << "顶点1" << "到顶点" << i << "的最短距离=" << Distance[i] << endl; } system("pause"); return 0; }
|