1
+ #include <stdio.h>
2
+ #define INFINITY 9999
3
+ #define MAX 10
4
+
5
+ void Dijkstra (int Graph [MAX ][MAX ], int n , int start ) {
6
+ int cost [MAX ][MAX ], distance [MAX ], pred [MAX ];
7
+ int visited [MAX ], count , mindistance , nextnode , i , j ;
8
+
9
+ // Creating cost matrix
10
+ for (i = 0 ; i < n ; i ++ )
11
+ for (j = 0 ; j < n ; j ++ ){
12
+ if (Graph [i ][j ] == 0 )
13
+ cost [i ][j ] = INFINITY ;
14
+ else
15
+ cost [i ][j ] = Graph [i ][j ];
16
+ }
17
+
18
+ for (i = 0 ; i < n ; i ++ ) {
19
+ distance [i ] = cost [start ][i ];
20
+ pred [i ] = start ;
21
+ visited [i ] = 0 ;
22
+ }
23
+
24
+ distance [start ] = 0 ;
25
+ visited [start ] = 1 ;
26
+ count = 1 ;
27
+
28
+ while (count < n - 1 ) {
29
+ mindistance = INFINITY ;
30
+
31
+ for (i = 0 ; i < n ; i ++ )
32
+ if (distance [i ] < mindistance && !visited [i ]) {
33
+ mindistance = distance [i ];
34
+ nextnode = i ;
35
+ }
36
+
37
+ visited [nextnode ] = 1 ;
38
+ for (i = 0 ; i < n ; i ++ )
39
+ if (!visited [i ])
40
+ if (mindistance + cost [nextnode ][i ] < distance [i ]) {
41
+ distance [i ] = mindistance + cost [nextnode ][i ];
42
+ pred [i ] = nextnode ;
43
+ }
44
+ count ++ ;
45
+ }
46
+
47
+ // Printing the distance
48
+ for (i = 0 ; i < n ; i ++ )
49
+ if (i != start ) {
50
+ printf ("\nDistance from source to %d: %d" , i , distance [i ]);
51
+ }
52
+ }
53
+ int main () {
54
+ int Graph [MAX ][MAX ], i , j , u , v , n , edges ;
55
+
56
+ printf ("Enter number of vertices in the graph : " );
57
+ scanf ("%d" , & n );
58
+
59
+ printf ("Enter number of edges in the graph: " );
60
+ scanf ("%d" , & edges );
61
+
62
+ for (i = 0 ;i < edges ;i ++ ){
63
+ printf ("From: " );
64
+ scanf ("%d" , & u );
65
+ printf ("To: " );
66
+ scanf ("%d" , & v );
67
+ printf ("Enter weight of edge from %d to %d: " , u , v );
68
+ scanf ("%d" , & Graph [u ][v ]);
69
+ }
70
+
71
+ printf ("Enter source vertex : " );
72
+ scanf ("%d" , & u );
73
+ Dijkstra (Graph , n , u );
74
+
75
+ return 0 ;
76
+ }
0 commit comments