diff --git a/Dijkstra's Algorithm.java b/Dijkstra's Algorithm.java new file mode 100644 index 0000000..4b070cb --- /dev/null +++ b/Dijkstra's Algorithm.java @@ -0,0 +1,78 @@ +import java.util.*; +public class Dijkstra { + class Graph { + LinkedList> adj[]; + int n; // Number of vertices. + Graph(int n) { + this.n = n; + adj = new LinkedList[n]; + for(int i = 0;i(); + } + // add a directed edge between vertices a and b with cost as weight + public void addEdgeDirected(int a, int b, int cost) { + adj[a].add(new Pair(b, cost)); + } + public void addEdgeUndirected(int a, int b, int cost) { + addEdgeDirected(a, b, cost); + addEdgeDirected(b, a, cost); + } + } + class Pair { + E first; + E second; + Pair(E f, E s) { + first = f; + second = s; + } + } + + // Comparator to sort Pairs in Priority Queue + class PairComparator implements Comparator> { + public int compare(Pair a, Pair b) { + return a.second - b.second; + } + } + + // Calculates shortest path to each vertex from source and returns the distance + public int[] dijkstra(Graph g, int src) { + int distance[] = new int[g.n]; // shortest distance of each vertex from src + boolean visited[] = new boolean[g.n]; // vertex is visited or not + Arrays.fill(distance, Integer.MAX_VALUE); + Arrays.fill(visited, false); + PriorityQueue> pq = new PriorityQueue<>(100, new PairComparator()); + pq.add(new Pair(src, 0)); + distance[src] = 0; + while(!pq.isEmpty()) { + Pair x = pq.remove(); // Extract vertex with shortest distance from src + int u = x.first; + visited[u] = true; + Iterator> iter = g.adj[u].listIterator(); + // Iterate over neighbours of u and update their distances + while(iter.hasNext()) { + Pair y = iter.next(); + int v = y.first; + int weight = y.second; + // Check if vertex v is not visited + // If new path through u offers less cost then update distance array and add to pq + if(!visited[v] && distance[u]+weight