本文实例为大家分享了C语言实现Floyd算法的具体代码,供大家参考,具体内容如下
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
|
#include <stdio.h> #include <stdlib.h> #include <limits.h> #define NUM 4 typedef struct MGraph /* 邻接表存储结构 */ { int edges[NUM][NUM]; int n,e; } MGraph; MGraph *build_mgraph(); void Floyd(MGraph *mgraph); void Ppath( int path[][NUM], int i, int j); void Dispath( int A[][NUM], int path[][NUM], int n); int main( void ) { MGraph *mgraph; printf ( "\n*************************************************************\n" ); printf ( "该图的矩阵表示为:\n" ); mgraph=build_mgraph(); printf ( "\n*************************************************************\n" ); printf ( "各顶点间最短路径为:\n" ); Floyd(mgraph); printf ( "\n*************************************************************\n" ); return 0; } MGraph *build_mgraph() { int i,j; int num_e=0; MGraph *mgraph=(MGraph *) malloc ( sizeof (MGraph)); int matrix[NUM][NUM]={{0,5,INT_MAX,7}, {INT_MAX,0,4,2}, {3,3,0,2}, {INT_MAX,INT_MAX,1,0}}; for (i=0;i<NUM;i++) { for (j=0;j<NUM;j++) { mgraph->edges[i][j]=matrix[i][j]; if (matrix[i][j]!=0 && matrix[i][j]!=INT_MAX) num_e++; } } mgraph->n=NUM; mgraph->e=num_e; printf ( "node=%d;edges=%d\n" ,mgraph->n,mgraph->e); for (i=0;i<NUM;i++) { for (j=0;j<NUM;j++) { if (mgraph->edges[i][j]!=INT_MAX) printf ( "%3d" ,mgraph->edges[i][j]); else printf ( "%3c" , '&' ); } printf ( "\n" ); } return mgraph; } void Floyd(MGraph *mgraph) { int A[NUM][NUM],path[NUM][NUM]; int i,j,k; for (i=0;i<mgraph->n;i++) { for (j=0;j<mgraph->n;j++) { A[i][j]=mgraph->edges[i][j]; path[i][j]=-1; } } for (k=0;k<mgraph->n;k++) { for (i=0;i<mgraph->n;i++) { for (j=0;j<mgraph->n;j++) { if (A[i][k]!=INT_MAX && A[k][j]!=INT_MAX && A[i][j]>A[i][k]+A[k][j]) { A[i][j]=A[i][k]+A[k][j]; path[i][j]=k; } } } } Dispath(A,path,mgraph->n); } void Ppath( int path[][NUM], int i, int j) { int k; k=path[i][j]; if (k==-1) return ; Ppath(path,i,k); printf ( "%d," ,k); Ppath(path,k,j); } void Dispath( int A[][NUM], int path[][NUM], int n) { int i,j; for (i=0;i<n;i++) { for (j=0;j<n;j++) { if (A[i][j]==INT_MAX) printf ( "%d-%d have no path" ,i,j); printf ( "%d-%d-%d: " ,i,j,A[i][j]); printf ( "%d," ,i); Ppath(path,i,j); printf ( "%d\n" ,j); } } } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://blog.csdn.net/xiaowang627/article/details/51592623