Dijkstra算法——单源最短路径
两种最常见的最短路径问题之一:求某个源点到其余各项顶点的最短路径
代码
1 #include <stdio.h> 2 int main() 3 { 4 int e[10][10], dis[10], book[10], i, j, n, m, t1, t2, t3, u, v, min; 5 int inf = 99999999; //正无穷值 6 //读入n和m,n表示顶点个数,m表示边的条数 7 scanf("%d %d", &n, &m); 8 9 //初始化 10 for (i = 1; i <= n; i++) 11 for (j = 1; j <= n; j++) 12 if (i == j) e[i][j] = 0; 13 else e[i][j] = inf; 14 15 //读入边 16 for (i = 1; i <= m; i++) 17 { 18 scanf("%d %d %d", &t1, &t2, &t3); 19 e[t1][t2] = t3; 20 } 21 22 //初始化dis数组,这里是1号顶点到其余各个顶点的初始路程 23 for (i = 1; i <= n; i++) 24 dis[i] = e[1][i]; 25 26 //book数组初始化 27 for (i = 1; i <= n; i++) 28 book[i] = 0; 29 book[i] = 1; 30 31 //Dijkstra算法核心语句 32 for (i = 1; i <= n - 1; i++) 33 { 34 //找到离1号顶点最近的顶点 35 min = inf; 36 for (j = 1; j <= n; j++) 37 { 38 if (book[j] == 0 && dis[j] < min) 39 { 40 min = dis[j]; 41 u = j; 42 } 43 } 44 45 book[u] = 1; 46 47 for (v = 1; v <= n; v++) 48 { 49 if (e[u][v] < inf) 50 { 51 if (dis[v] > dis[u] + e[u][v]) 52 dis[v] = dis[u] + e[u][v]; 53 } 54 } 55 } 56 57 //输出最终的结果 58 for (i = 1; i <= n; i++) 59 { 60 printf(" %d ", dis[i]); 61 } 62 63 getchar(); 64 getchar(); 65 return 0; 66 }