Skip to content

Instantly share code, notes, and snippets.

@myrtleTree33
Created April 19, 2020 13:39
Show Gist options
  • Save myrtleTree33/260e1b983bc7f1363fb38896bfbff585 to your computer and use it in GitHub Desktop.
Save myrtleTree33/260e1b983bc7f1363fb38896bfbff585 to your computer and use it in GitHub Desktop.
Dijkstra's shortest distance in Java
import java.util.HashSet;
import java.util.Set;
public class Djistrika {
public static final int V = 9;
public static void dijkstra(int[][] graph, int ref) {
// Initialize vars
final int VV = graph.length;
Set<Integer> explored = new HashSet<>();
int[] dist = new int[VV];
// Initialize dist array
// Always set source to 0 (dist[0] = 0)
for (int i = 1; i < VV; i++) {
dist[i] = Integer.MAX_VALUE;
}
// At most, we iterate across all vertices.
for (int i = 0; i < VV - 1; i++) {
int node = chooseNextNode(dist, explored);
explored.add(node);
for (int j = 0; j < VV; j++) {
if (!explored.contains(j)
&& graph[i][j] != 0 // in set
&& dist[i] != Integer.MAX_VALUE // there is path from 0 to i previously
&& dist[i] + graph[i][j] < dist[j] // there is a path from i to j, and lesser than dist from 0 to j
) {
dist[j] = dist[i] + graph[i][j];
}
}
}
printDists(dist);
}
private static int chooseNextNode(int[] dists, Set<Integer> explored) {
int min = Integer.MAX_VALUE;
int node = -1;
for (int i = 0; i < dists.length; i++) {
if (!explored.contains(i) && dists[i] < min) {
node = i;
}
}
return node;
}
private static void printDists(int[] dist) {
for (int i = 0; i < dist.length; i++) {
System.out.println(String.format("Ref=%d Dist=%d", i, dist[i]));
}
}
public static void main(String[] arg) {
int graph[][] = {{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 14, 10, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}};
dijkstra(graph, 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment