Dijkstra's Algorithm in Graph

Welcome to our beginner's guide to Dijkstra's Algorithm in Graph Theory! Dijkstra's Algorithm is a fundamental method used to find the shortest path between nodes in a graph, particularly in graphs with non-negative edge weights. Let's explore this powerful algorithm together!

Understanding the Problem Statement

Before diving into Dijkstra's Algorithm, let's understand the problem it addresses. In graph theory, finding the shortest path between two vertices is a common task. This problem is particularly important in various applications such as network routing, transportation systems, and GPS navigation.

The shortest path between two vertices in a graph is defined as the path with the minimum total edge weight. Dijkstra's Algorithm efficiently finds the shortest path from a source vertex to all other vertices in the graph.

What is Dijkstra's Algorithm?

Dijkstra's Algorithm is a greedy algorithm used to find the shortest path from a single source vertex to all other vertices in a weighted graph with non-negative edge weights. The algorithm maintains a set of vertices whose shortest distance from the source vertex is already known and continually expands this set by considering neighboring vertices.

Dijkstra's Algorithm is named after Dutch computer scientist Edsger W. Dijkstra, who first proposed it in 1956.

How does Dijkstra's Algorithm Work?

Dijkstra's Algorithm operates as follows:

  1. Initialize distances from the source vertex to all other vertices as infinity, except for the source vertex itself (which has a distance of 0).
  2. Initialize a priority queue to store vertices based on their tentative distances from the source vertex.
  3. While the priority queue is not empty:
    • Extract the vertex with the smallest tentative distance from the priority queue.
    • For each neighboring vertex of the extracted vertex:
      • Calculate the tentative distance from the source vertex through the extracted vertex to the neighboring vertex.
      • If the calculated distance is smaller than the current distance, update the distance and update the priority queue accordingly.
  4. After processing all vertices, the shortest distances from the source vertex to all other vertices are known.

Dijkstra's Algorithm ensures that once a vertex is processed, its shortest distance from the source vertex is finalized and does not change during subsequent iterations.

Dijkstra's Algorithm Example

Let's explore Dijkstra's Algorithm step by step to find the shortest path in the following weighted graph:


          A---4---B
         /|    /  |
        2 |   5   | 1
       /  |  /    |/
      C --3--D----E

Dijkstra's Algorithm Steps:

  1. Start with a source node and initialize the distance to all other nodes as infinity, except the source itself (0).
  2. Distances: {A: 0, B: ∞, C: ∞, D: ∞, E: ∞}
  3. Visit the source node (A) and update the distances to its neighbors.
  4. Distances: {A: 0, B: 4, C: 2, D: 3, E: ∞}
  5. Choose the node with the smallest distance (C) and mark it as visited.
  6. Visited: [A, C], Current Node: C
  7. Update the distances to C's unvisited neighbors (D).
  8. Distances: {A: 0, B: 4, C: 2, D: 5, E: ∞}
  9. Continue this process:
    • Choose the next node with the smallest distance (B) and mark it as visited.
    • Visited: [A, C, B], Current Node: B
    • Update the distances to B's unvisited neighbors (D, E).
    • Distances: {A: 0, B: 4, C: 2, D: 5, E: 5}
    • Choose the next node with the smallest distance (D) and mark it as visited.
    • Visited: [A, C, B, D], Current Node: D
    • Update the distances to D's unvisited neighbors (E).
    • Distances: {A: 0, B: 4, C: 2, D: 5, E: 6}
    • Choose the last node with the smallest distance (E) and mark it as visited.
    • Visited: [A, C, B, D, E], Current Node: E

The final shortest distances from node A to all other nodes are:

{A: 0, B: 4, C: 2, D: 5, E: 6}

To find the shortest path from A to any node, follow the path with the smallest distances.

Example Application of Dijkstra's Algorithm

Consider a scenario where you have a road network with cities as vertices and road segments as edges, each with a corresponding distance or travel time. By applying Dijkstra's Algorithm, you can efficiently determine the shortest travel time or distance from a given city to all other cities in the network.

Implementing Dijkstra's Algorithm in Code

Now, let's take a look at how we can implement Dijkstra's Algorithm in code. We'll provide examples in several programming languages to help you get started:


package codeKatha;

import java.util.*;

public class DijkstraSP {
    public int[] dijkstraSP(Graph graph, int source) {
        int[] dist = new int[graph.size()];
        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[source] = 0;

        PriorityQueue<Integer> minHeap = new PriorityQueue<>((a, b) -> dist[a] - dist[b]);
        minHeap.offer(source);

        while (!minHeap.isEmpty()) {
            int u = minHeap.poll();
            for (Edge edge : graph.getEdges(u)) {
                int v = edge.destination;
                int weight = edge.weight;
                if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) {
                    dist[v] = dist[u] + weight;
                    minHeap.offer(v);
                }
            }
        }

        return dist;
    }
}

#include <iostream>
#include <vector>
#include <queue>
#include "Graph.h"

class DijkstraSP {
public:
    std::vector<int> dijkstraSP(Graph& graph, int source) {
        std::vector<int> dist(graph.size(), INT_MAX);
        dist[source] = 0;

        std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<>> minHeap;
        minHeap.push({0, source});

        while (!minHeap.empty()) {
            int u = minHeap.top().second;
            minHeap.pop();
            for (Edge edge : graph.getEdges(u)) {
                int v = edge.destination;
                int weight = edge.weight;
                if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) {
                    dist[v] = dist[u] + weight;
                    minHeap.push({dist[v], v});
                }
            }
        }

        return dist;
    }
};

import heapq

class DijkstraSP:
    def dijkstraSP(self, graph, source):
        dist = [float('inf')] * len(graph)
        dist[source] = 0

        min_heap = [(0, source)]

        while min_heap:
            d, u = heapq.heappop(min_heap)
            if d > dist[u]:
                continue
            for edge in graph[u]:
                v, weight = edge
                if dist[u] + weight < dist[v]:
                    dist[v] = dist[u] + weight
                    heapq.heappush(min_heap, (dist[v], v))

        return dist

class DijkstraSP {
    dijkstraSP(graph, source) {
        const dist = new Array(graph.size()).fill(Infinity);
        dist[source] = 0;

       

 const minHeap = new PriorityQueue((a, b) => dist[a] - dist[b]);
        minHeap.offer(source);

        while (!minHeap.isEmpty()) {
            const u = minHeap.poll();
            for (const edge of graph.getEdges(u)) {
                const v = edge.destination;
                const weight = edge.weight;
                if (dist[u] !== Infinity && dist[u] + weight < dist[v]) {
                    dist[v] = dist[u] + weight;
                    minHeap.offer(v);
                }
            }
        }

        return dist;
    }
}

Graph: Concept and Important Algorithms

1. Basics of Graph Data Structure
2. Breadth-First Search (BFS) in Graph
3. Depth-First Search (DFS) in Graph 
4. Topological Sort in Graph
5. Union-Find Algorithm in Graph
6. Prim's Algorithm in Graph 
7. Dijkstra's Algorithm in Graph
8. Kruskal's Algorithm in Graph

Congratulations! You've now learned the basics of Dijkstra's Algorithm in graph theory. Feel free to experiment with the provided code examples and explore further applications of Dijkstra's Algorithm in your projects.

Comments

Popular Posts on Code Katha

Java Interview Questions for 10 Years Experience

Sql Interview Questions for 10 Years Experience

Spring Boot Interview Questions for 10 Years Experience

Visual Studio Code setup for Java and Spring with GitHub Copilot

Java interview questions - Must to know concepts

Spring Data JPA

Data Structures & Algorithms Tutorial with Coding Interview Questions

Elasticsearch Java Spring Boot

Java interview questions for 5 years experience