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