dijstra算法,C实现
原理请看
https://www.cnblogs.com/biyeymyhjob/archive/2012/07/31/2615833.html
C代码:
#define MAXSIZE 1001 #define MAXNUM 10 int dist[MAXNUM] = {0};//到达该点的最短路长 int prev[MAXNUM] = {0};//该点的前驱结点 int A[MAXNUM][MAXNUM] = {0}; void dijstra(int start) { bool s[MAXNUM]; int n = MAXNUM; //初始化 for(int i=1;i<=n;i++) { dist[i] = A[start][i]; s[i] = false; if(dist[i] == MAXSIZE) prev[i] = -1; else prev[i] = start; } dist[start] = 0; s[start] = true; for(int i=2;i<=n;i++) { int mindist = MAXSIZE; int u = start; for(int j=1;j<=n;j++) { if(!s[j] && dist[j]<mindist) { u = j; mindist = dist[j]; } } s[u] = true; for(int j=1;j<=n;j++) { if(!s[j] && A[u][j]<MAXSIZE) { if(dist[u] + A[u][j] < dist[j]) { dist[j] = dist[u] + A[u][j]; prev[j] = u; } } } } }
PS:该图是用邻接矩阵实现的。