-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathshortestpath_dij.c
110 lines (91 loc) · 2.35 KB
/
shortestpath_dij.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <stdio.h>
#include <stdlib.h>
#define NO 0
#define YES 1
#define MAX 1000
#define INF 999999
struct node {
int adj_node;
int adj_node_val;
struct node *next_adjacent;
} node;
typedef struct node NODE;
NODE *arr[MAX];
int dist[MAX];
int visited[MAX];
int returnMin(int num)
{
int k;
int min = INF;
int minnode = 0;
for(k=0; k <num; k++) {
if (dist[k] < min && visited[k] == NO) {
min = dist[k];
minnode = k;
}
}
return minnode;
}
void dik(int num)
{
int node;
for(node=0; node < num; node++) {
int min = returnMin(num);
printf("Min node [%d]\n", min);
NODE *startnode = arr[min];
visited[min] = YES;
while (startnode) {
if (visited[startnode->adj_node] == NO) {
if (dist[startnode->adj_node] > startnode->adj_node_val + dist[min])
dist[startnode->adj_node] = startnode->adj_node_val + dist[min];
}
startnode = startnode->next_adjacent;
}
}
}
int main()
{
int r;
int c;
int val;
NODE *cur = NULL;
int k;
int num;
printf("Welcome to dij algorithm..\n");
printf("Enter number of nodes in the graph..\n");
scanf("%d", &num);
/* Initialize distance and visited arrays */
for(k=0; k < num; k++) {
visited[k] = NO;
dist[k] = INF;
arr[k] = NULL;
}
for(r=0; r< num; r++) {
for(c=0; c<num;c++) {
scanf("%d", &val);
if (val) {
/**/
if (!arr[r]) {
arr[r] = (NODE*) malloc(sizeof(NODE));
arr[r]->adj_node = c;
arr[r]->adj_node_val = val;
arr[r]->next_adjacent = NULL;
cur = arr[r];
} else {
cur->next_adjacent = (NODE*) malloc(sizeof(NODE));
cur->next_adjacent->adj_node = c;
cur->next_adjacent->adj_node_val = val;
cur->next_adjacent->next_adjacent = NULL;
cur = cur->next_adjacent;
}
}
}
}
int startnode = 0;
dist[startnode] = 0;
dik(num);
for(k=0; k <num; k++) {
printf("Distance from 0 to %d is [%d]\n", k, dist[k]);
}
printf("Anupam...exit...");
}