Skip to main content

Introduction of Dijkstra's algorithm

What is Dijkstra's algorithm ?

Dijkstra's algorithm is an algorithm for finding the shortest path from source node to all other nodes in a weighted graph. that's why we called this algorithm as a Single Source Shortest Path.

note

weights should be non-negative otherwise it will create a negative weight cycle which in turns produce the infinite loop

Example

Lets take a weighted and undirected graph for illustration

Graph Representation

image

Input:

V(Vertex) = 3 , E(Edges) = 3 , S(Source) = 2
edges[][] = [ [0,1,1] , [1,2,3] , [0,2,6] ]

Output:

dis[] -> [4 , 3 , 0]
index -> [0 , 1 , 2]

edges[i] = [u,v,w], where u and v are nodes and w is distance between u and v.

dis[i] = distance between node i and source node

Convert input edges into adjacency list

generally in problem solving questions related to graph we are provided the edges in the input, but that's not the actual representation of graph.

actual representation of graph is adjacency list or adjacency matrix.

hence we need to convert input edges into adjacency list.

Working of Algorithm

  1. mark the distance to each node as infinity, except for the source node, which is marked as 0.
  2. Start from the source node and mark it as current node and enter it into min heap priority queue.
  3. pull the node from min heap priority queue
    • calculate the distance to that neighbor using distance upto current node + distance from current to neighbor node
    • If this distance is less than the neighbor's current distance, update the neighbor's distance and put it into min heap priority queue.
  4. repeat step 3 until we have node in min heap priority queue

Intution of Algorithm

We use a min heap priority queue because it allows us to efficiently access the vertex with the smallest distance from the source vertex.

In the context of Dijkstra's algorithm, we can store each vertex in the min heap priority queue along with its current distance from the source vertex.

By maintaining this min heap property, we ensure that the vertex with the smallest distance is always at the top of the heap, so we can easily access and explore the next vertex with the smallest distance.

Code

import java.util.*;

class Main{
// main function
public static int[] dijkstra(int V, ArrayList<ArrayList<int[]>> adj, int S)
{
int[] dis = new int[V];// distance array
// distance from source to all other nodes is infinite for now except source node
for(int i=0;i<V;i++){
if(S!=i)dis[i] = Integer.MAX_VALUE;
}
// Priority Queue to select the shortest distance first, min-heap priority queue
PriorityQueue<Node> pq = new PriorityQueue<>((a,b)->a.dis-b.dis);
pq.add(new Node(S,0));// add source node to S and dis to be 0
while(!pq.isEmpty()){
Node element = pq.poll();// poll the node
int node = element.node,wt = element.dis;
// get all the neighbour of node
ArrayList<int[]> neighbours = adj.get(node);
for (int[] neigh : neighbours) {
int neigh_node = neigh[0] , dis_from_node = neigh[1];
// if we have a path to get minimum distance
if(wt+dis_from_node < dis[neigh_node]){
dis[neigh_node] = wt+dis_from_node;
pq.add(new Node(neigh_node,dis[neigh_node]));
}
}
}
return dis;
}
public static ArrayList<ArrayList<int[]>> createGraph(int V,int E,int[][] edges){
ArrayList<ArrayList<int[]>> adj = new ArrayList<>();
// there are V nodes
for(int i=0;i<V;i++){
adj.add(new ArrayList<>());
}
// iterate through all the edges
for(int i=0;i<E;i++){
int[] edge = edges[i];
int u = edge[0],v = edge[1],w = edge[2];
adj.get(u).add(new int[]{v,w});// connect u to v with weight w
adj.get(v).add(new int[]{u,w});// connect v to u with weight w
}
return adj;
}
public static void main(String args[]){
// input section
int V = 3,E = 3,S = 2;// V is number of nodes and E is number of edges, S is source node
int[][] edges = {{0,1,1},{1,2,3},{0,2,6}};// each array consists of {u,v,w}
ArrayList<ArrayList<int[]>> adj = createGraph(V,E,edges);
int[] res = dijkstra(V, adj, S);
// print output
for(int r: res)System.out.print(r+" ");
}
}

class Node{
int node, dis;
Node(int _node,int _dis){
this.node = _node;
this.dis = _dis;
}
}

Complexity

Time Complexity:

O(Vlog(V) + E)

Space Complexity:

O(V + E)

note

V denotes number of Vertex/Nodes and E denotes number of Edges in a Graph.

Problem Solving Questions