1
+ using System ;
2
+ using System . Collections . Generic ;
3
+ using System . Linq ;
4
+ using System . Text ;
5
+ using System . Diagnostics ;
6
+
7
+ namespace DijkstraAlgorithm
8
+ {
9
+ class Dijkstra
10
+ {
11
+
12
+ private static int MinimumDistance ( int [ ] distance , bool [ ] shortestPathTreeSet , int verticesCount )
13
+ {
14
+ int min = int . MaxValue ;
15
+ int minIndex = 0 ;
16
+
17
+ for ( int v = 0 ; v < verticesCount ; ++ v )
18
+ {
19
+ if ( shortestPathTreeSet [ v ] == false && distance [ v ] <= min )
20
+ {
21
+ min = distance [ v ] ;
22
+ minIndex = v ;
23
+ }
24
+ }
25
+
26
+ return minIndex ;
27
+ }
28
+
29
+ private static void OutputDistance ( int [ ] distance , int verticesCount )
30
+ {
31
+ Console . WriteLine ( "Vertex Distance from source" ) ;
32
+
33
+ for ( int i = 0 ; i < verticesCount ; ++ i )
34
+ Console . WriteLine ( "{0}\t {1}" , i , distance [ i ] ) ;
35
+ }
36
+
37
+ public static void DijkstraAlgo ( int [ , ] graph , int source , int verticesCount )
38
+ {
39
+ int [ ] distance = new int [ verticesCount ] ;
40
+ bool [ ] shortestPathTreeSet = new bool [ verticesCount ] ;
41
+
42
+ for ( int i = 0 ; i < verticesCount ; ++ i )
43
+ {
44
+ distance [ i ] = int . MaxValue ;
45
+ shortestPathTreeSet [ i ] = false ;
46
+ }
47
+
48
+ distance [ source ] = 0 ;
49
+
50
+ for ( int count = 0 ; count < verticesCount - 1 ; ++ count )
51
+ {
52
+ int u = MinimumDistance ( distance , shortestPathTreeSet , verticesCount ) ;
53
+ shortestPathTreeSet [ u ] = true ;
54
+
55
+ for ( int v = 0 ; v < verticesCount ; ++ v )
56
+ if ( ! shortestPathTreeSet [ v ] && Convert . ToBoolean ( graph [ u , v ] ) && distance [ u ] != int . MaxValue && distance [ u ] + graph [ u , v ] < distance [ v ] )
57
+ distance [ v ] = distance [ u ] + graph [ u , v ] ;
58
+ }
59
+
60
+ OutputDistance ( distance , verticesCount ) ;
61
+ }
62
+
63
+ static void Main ( string [ ] args )
64
+ {
65
+ int [ , ] graph = {
66
+ { 0 , 6 , 0 , 0 , 0 , 0 , 0 , 9 , 0 } ,
67
+ { 6 , 0 , 9 , 0 , 0 , 0 , 0 , 11 , 0 } ,
68
+ { 0 , 9 , 0 , 5 , 0 , 6 , 0 , 0 , 2 } ,
69
+ { 0 , 0 , 5 , 0 , 9 , 16 , 0 , 0 , 0 } ,
70
+ { 0 , 0 , 0 , 9 , 0 , 10 , 0 , 0 , 0 } ,
71
+ { 0 , 0 , 6 , 0 , 10 , 0 , 2 , 0 , 0 } ,
72
+ { 0 , 0 , 0 , 16 , 0 , 2 , 0 , 1 , 6 } ,
73
+ { 9 , 11 , 0 , 0 , 0 , 0 , 1 , 0 , 5 } ,
74
+ { 0 , 0 , 2 , 0 , 0 , 0 , 6 , 5 , 0 }
75
+ } ;
76
+
77
+ DijkstraAlgo ( graph , 0 , 9 ) ;
78
+ }
79
+ }
80
+ }
0 commit comments