O(N^3)
,而本文要介绍的Dijkstra算法时间复杂度是O(N^2),而且会在后续的堆里介绍优化本算法的方式。当数据过大时,Floyd-Warshall就不能再规定时间内完成了。#include<stdio.h> int a[2000][2000]; int inf = 99999999; int dis[2000], book[2000]; int main() { int i, j, k, m, n, x, y, s, u, v; int min; scanf("%d %d", &n, &m); /* */ //初始化 for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) if (i == j) a[i][j] = 0; else a[i][j] = inf; //读入边(有向图) for (i = 1; i <= m; i++) { scanf("%d %d %d", &x, &y, &s); a[x][y] = s; } for (i = 1; i <= n; i++) dis[i] = a[1][i]; for (i = 1; i <= n; i++) book[i] = 0; book[1] = 1; //Dijkstra 算法核心语句 for (i = 1; i <= n; i++) { //找到离1号顶点最近的点 min = inf; for (j = 1; j <= n; j++) { if (book[j] == 0 && dis[j] < min) { min = dis[j]; u = j; } } book[u] = 1; for (v = 1; v <= n; v++) { if (a[u][v] < inf) { if (dis[v] > dis[u] + a[u][v]) { dis[v] = dis[u] + a[u][v]; } } } } for (i = 1; i <= n; i++) { printf("%d ", dis[i]); } return 0; }
运行结果: