Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

import java.util.

Arrays;
import java.util.List;
import java.util.PriorityQueue;
public class Dijkstra {
static final int INF = Integer.MAX_VALUE/3;
static void shortestPath(List<Integer>[] adj, List<Integer>[] w, int[] p
i, int[] d, int s){
Arrays.fill(pi, -1);
Arrays.fill(d, INF);
boolean[] visited = new boolean[pi.length];
d[s] = 0;
PriorityQueue<Pair> pq = new PriorityQueue<Pair>();
pq.add(new Pair(0, s));
int nVisited = 0;
while (!pq.isEmpty() && nVisited != pi.length) {
int u = pq.poll().b;
if (visited[u]) continue;
visited[u] = true;
nVisited++;
for (int i = 0; i < adj[u].size(); i++) {
int v = adj[u].get(i);
if (!visited[v]){
int cost = d[u] + w[u].get(i);
if (d[v] > cost){
d[v] = cost;
pi[v] = u;
pq.add(new Pair(d[v], v));
}
}
}
}
}
static class Pair implements Comparable<Pair> {
int a, b;
public Pair(int a, int b){
this.a = a;
this.b = b;
}
public int compareTo(Pair o) {
if (a<o.a) return -1;
if (a>o.a) return 1;
return 0;
}
}

You might also like