Skip to content

Instantly share code, notes, and snippets.

@soundsmitten
Created December 12, 2012 22:41
Show Gist options
  • Select an option

  • Save soundsmitten/4272332 to your computer and use it in GitHub Desktop.

Select an option

Save soundsmitten/4272332 to your computer and use it in GitHub Desktop.
Java- Dijkstra's algorithm
// 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