Skip to content

Instantly share code, notes, and snippets.

@andriybuday
Last active February 7, 2020 03:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andriybuday/bf3cd52008dd100a1d7f0cafd05761ee to your computer and use it in GitHub Desktop.
Save andriybuday/bf3cd52008dd100a1d7f0cafd05761ee to your computer and use it in GitHub Desktop.
Djikstra
boolean[] visited = new boolean[N+1];
// [distance, toNode]
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> (a[0] - b[0]));
pq.add(new int[]{0, startNode});
while(!pq.isEmpty()) {
int[] current = pq.poll();
int node = current[1];
int dist = current[0];
// if reached target node, return dist, or if task is to cover entire graph continue
if(!visited[node]) {
visited[node] = true;
Map<Integer, Integer> connections = graph.get(node);
if(connections != null) {
for(int next: connections.keySet()) {
pq.add(new int[]{dist + connections.get(next), next});
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment