Last active
February 7, 2020 03:07
-
-
Save andriybuday/bf3cd52008dd100a1d7f0cafd05761ee to your computer and use it in GitHub Desktop.
Djikstra
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
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