#include <stdio.h>
#define maxnodenum 100
#define maxedgenum 100
#define MAX_VALUE 200
int matrix[maxnodenum][maxnodenum];
int nodes[maxnodenum], dist[maxnodenum], prev[maxnodenum];
int nodenum, edgenum;
static void matrix_init(void);
static void dijkstra(int v);
static void print_dijkstra(int v, int e);
int main(int argc, char **argv)
{ int v, e;
matrix_init();
printf("Input source node: ");
scanf("%d", &v);
getchar();
dijkstra(v);
printf("Input end node: ");
scanf("%d", &e);
getchar();
print_dijkstra(v, e);
return(0);
}
static void matrix_init(void)
{
int i, j, row, col, weight;
printf("Input nodenum and edgenum:\n");
scanf("%d %d", &nodenum, &edgenum);
getchar();
for(i = 1; i <= nodenum; i++){
for(j = 1; j <= nodenum; j++){
matrix[i][j] = MAX_VALUE;
}
}
printf("Input all edges:\n");
for(i = 0; i < edgenum; i++){
scanf("%d %d %d", &row, &col, &weight);
getchar();
matrix[row][col] = weight;
}
}
static void dijkstra(int v)
{
int i, j, u, temp, newdist;
for(i = 1; i <= nodenum; i++){
dist[i] = matrix[v][i];
if((dist[i] == MAX_VALUE)){
prev[i] = 0;
}
else{
prev[i] = v;
}
}
nodes[v] = 1;
for(i = 1; i < nodenum; i++){
temp = MAX_VALUE;
u = v;
for(j = 1; j <= nodenum; j++){
if((!nodes[j]) && (dist[j] < temp)){
temp = dist[j];
u = j;
}
}
nodes[u] = 1;
for(j = 1; j <= nodenum; j++){
if((!nodes[j]) && (matrix[u][j] < MAX_VALUE)){
newdist = matrix[u][j] + dist[u];
if(newdist < dist[j]){
dist[j] = newdist;
prev[j] = u;
}
}
}
}
}
static void print_dijkstra(int v, int e)
{
int i;
printf("The shortest path from node %d to node %d is: ", v, e);
printf("%d", e);
for(i = e; i != v; i = prev[i]){
printf("<-%d", prev[i]);
}
printf("\n");
}
|