Created
December 12, 2012 22:41
-
-
Save soundsmitten/4272332 to your computer and use it in GitHub Desktop.
Java- Dijkstra's algorithm
This file contains hidden or 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
| // From Wikipedia: For a given source vertex (node) in the graph, Dijkstra's algorithm finds the | |
| // path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. | |
| void Dijkstra(int n, int [][] W, int source, int[] touch, int[] distance, int[totalCost]) | |
| { | |
| int [] length | |
| for(int i = 1; i<=n; i++) | |
| { | |
| touch[i] = source | |
| length[i] = W[source][i] | |
| } | |
| for(j=1; j<=n-1;j++) { | |
| min = infinity | |
| for (int i = 1; i <=n; i++) | |
| { | |
| if (length[i] < min && length[i] > 0) | |
| { | |
| min = length[i]; | |
| vnear = i; | |
| } | |
| } | |
| for (i = 1; i<=n; i++) { | |
| if (length[vnear] + W[vnear][i] < length[i]) | |
| { | |
| touch[i] = vnear; | |
| length[i] = length[vnear] + W [vnear][i]; | |
| } | |
| } | |
| totalCost[vnear] = length[vnear]; | |
| length[vnear] = 0 | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment