classExample {Map<Integer,List<int[]>> G; // G is a mapping of sourceVertex: [targetVertex, weight]voiddijkstra(int source,int target) {// PQ with [targetVertex, weight]. Sorted by weights in non-decreasing orderPriorityQueue<int[]> minHeap =newPriorityQueue<>((a, b) -> a[1] - b[1]);minHeap.add(newint[] {source,0});int[] minDist =newint[G.size()];Arrays.fill(minDist,Integer.MAX_VALUE); // Fill with maxiumum value minDist[source] =0;while (minHeap.isEmpty()) {int cur =minHeap.remove()[0];if (!G.containsKey(cur)) continue; // No edgesfor (int[] nextEdge :G.get(cur)) {int nextVertex = nextEdge[0], nextWeight = nextEdge[1];if (minDist[nextVertex] > minDist[cur] + nextWeight) { minDist[nextVertex] = minDist[cur] + nextWeight;minHeap.add(newint[] {nextVertex, minDist[nextVertex]}); } } } }}
Time: O(ElogV)
Space: O(V)
Works only with non-negative weights.
Bellman-Ford
classExample {List<int[]> edges; // edges is a list of: [source, target, weight]intbellmanFord(int source,int target,int size) {// Size is the number of verticesint[] prev =newint[size], cur =newint[size];Arrays.fill(prev,Integer.MAX_VALUE);Arrays.fill(cur,Integer.MAX_VALUE); prev[source] =0;for (int i =0; i < size; i++) { // V passes cur[source] =0;for (int[] edge : edges) {int src = edge[0], tar = edge[1], weight = edge[2];if (cur[src] !=Integer.MAX_VALUE&& prev[src] + weight < cur[tar]) { cur[tar] = prev[src] + weight; } } prev =cur.clone(); }return cur[target] ==Integer.MAX_VALUE?-1: cur[target]; // Shortest dist: (source -> target) }}
Time: O(EV)
Space: O(V)
Can also work with negative weights but cannot work with negative cycles.
While Dijkstra uses a Priority Queue to greedily select the closest non-processed vertex, bellman-ford simply relaxes all edges leaving any vertex in any order.
Bellman-Ford with Queue (Shortest Faster Path Algorithm)