<P>/*<BR>* File: shortest.c<BR>* Description: 网络中两点最短路径 Dijkstra 算法<BR>* Shortest Path Dijkstra Algorithm<BR>* Created: 2001/11/25<BR>* Author: Justin Hou [mailtjustin_hou@hotmail.com]<BR>*/</P>
<P>#include <stdio.h><BR>#define true 1<BR>#define false 0<BR>#define I 9999 /* 无穷大 */<BR>#define N 20 /* 城市顶点的数目 */</P>
<P>int cost[N][N] = {<BR> {0,3,I,I,I,1,I,I,I,I,I,I,I,I,I,I,I,I,I,I},<BR> {3,0,5,I,I,I,6,I,I,I,I,I,I,I,I,I,I,I,I,I},<BR> {I,5,0,4,I,I,I,1,I,I,I,I,I,I,I,I,I,I,I,I},<BR> {I,I,4,0,2,I,I,I,6,I,I,I,I,I,I,I,I,I,I,I},<BR> {I,I,I,2,0,I,I,I,I,7,I,I,I,I,I,I,I,I,I,I},<BR> {1,I,I,I,I,0,1,I,I,I,2,I,I,I,I,I,I,I,I,I},<BR> {I,6,I,I,I,1,0,6,I,I,I,7,I,I,I,I,I,I,I,I},<BR> {I,I,1,I,I,I,6,0,2,I,I,I,3,I,I,I,I,I,I,I},<BR> {I,I,I,6,I,I,I,2,0,8,I,I,I,4,I,I,I,I,I,I},<BR> {I,I,I,I,7,I,I,I,8,0,I,I,I,I,5,I,I,I,I,I},<BR> {I,I,I,I,I,2,I,I,I,I,0,4,I,I,I,3,I,I,I,I},<BR> {I,I,I,I,I,I,7,I,I,I,4,0,3,I,I,I,4,I,I,I},<BR> {I,I,I,I,I,I,I,3,I,I,I,3,0,3,I,I,I,5,I,I},<BR> {I,I,I,I,I,I,I,I,4,I,I,I,3,0,7,I,I,I,2,I},<BR> {I,I,I,I,I,I,I,I,I,5,I,I,I,7,0,I,I,I,I,3},<BR> {I,I,I,I,I,I,I,I,I,I,3,I,I,I,I,0,5,I,I,I},<BR> {I,I,I,I,I,I,I,I,I,I,I,4,I,I,I,5,0,8,I,I},<BR> {I,I,I,I,I,I,I,I,I,I,I,I,5,I,I,I,8,0,6,I},<BR> {I,I,I,I,I,I,I,I,I,I,I,I,I,2,I,I,I,6,0,4},<BR> {I,I,I,I,I,I,I,I,I,I,I,I,I,I,3,I,I,I,4,0}<BR>};<BR>int dist[N]; /* 存储当前最短路径长度 */<BR>int v0 = 'A' - 65; /* 初始点是 A */</P>
<P>void main()<BR>{<BR> int final[N], i, v, w, min;</P>
<P> /* 初始化最短路径长度数据,所有数据都不是最终数据 */<BR> for (v = 0; v < N; v++) {<BR> final[v] = false;<BR> dist[v] = cost[v0][v];<BR> }</P>
<P> /* 首先选v0到v0的距离一定最短,最终数据 */<BR> final[v0] = true;</P>
<P> /* 寻找另外 N-1 个结点 */<BR> for (i = 0; i < N-1; i++) {<BR> min = I; /* 初始最短长度无穷大 */<BR> <BR> /* 寻找最短的边 */<BR> for (w = 0; w < N; w++) {<BR> if (!final[w] && dist[w] < min) {<BR> min = dist[w];<BR> v = w;<BR> }<BR> }<BR> final[v] = true; /* 加入新边 */</P>
<P> for (w = 0; w < N; w++) { /* 更新 dist[] 数据 */<BR> if (!final[w] && dist[v] + cost[v][w] < dist[w]) {<BR> dist[w] = dist[v] + cost[v][w];<BR> }<BR> }<BR> }</P>
<P> for (i = 0; i < N; i++) { /* 显示到监视器 */<BR> printf("%c->%c: %2d\t", v0 + 65, i + 65, dist);<BR> }<BR>}</P> |