Created
April 11, 2018 07:32
-
-
Save serge-medvedev/d6246693a4f594fd31c9c8cb012029b8 to your computer and use it in GitHub Desktop.
Dijkstra's Shortest Path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int findNearest( int distances[], bool spt_flags[] ) | |
{ | |
auto min_value = numeric_limits< int >::max(), min_index = 0; | |
for ( auto v = 0; v < N; v++ ) | |
{ | |
auto not_in_spt = ( ! spt_flags[ v ] ); | |
auto closer = ( distances[ v ] < min_value ); | |
if ( not_in_spt && closer ) | |
{ | |
min_value = distances[ v ], | |
min_index = v; | |
} | |
} | |
return min_index; | |
} | |
void findShortestPaths( int graph[ N ][ N ], int source ) | |
{ | |
auto distances = new int [ N ]; | |
auto spt_flags = new bool [ N ]; | |
for ( auto i = 0; i < N; i++ ) | |
{ | |
distances[ i ] = numeric_limits< int >::max(), | |
spt_flags[ i ] = false; | |
} | |
distances[ source ] = 0; | |
for ( auto count = 0; count < ( N - 1 ); count++ ) | |
{ | |
auto u = findNearest( distances, spt_flags ); | |
spt_flags[ u ] = true; | |
for ( auto v = 0; v < N; v++ ) | |
{ | |
auto not_in_spt = ( ! spt_flags[ v ] ); | |
auto connected = ( graph[ u ][ v ] > 0 ); | |
auto initialized = ( distances[ u ] < numeric_limits< int >::max() ); | |
if ( not_in_spt && connected && initialized ) | |
{ | |
distances[ v ] = min( distances[ v ], distances[ u ] + graph[ u ][ v ] ); | |
} | |
} | |
} | |
// 'distances' will contain all the shortest paths from 'source' to other vertices. | |
delete [] spt_flags; | |
delete [] distances; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment