Dijkstra’s Algorithm in Data Structure: Step-by-Step Example

Data Structure / Graph Algorithms Chapter 59

Find the Shortest Route, One Step at a Time.

Imagine travelling from your college to six nearby places. Several roads are available, but every road takes a different amount of time. Which route will take the least total time?

That is the problem solved by Dijkstra's Algorithm. Many students find the algorithm confusing because the distance values keep changing. Here we will understand why they change, when a distance becomes final, and how to find the shortest route.

What Is Dijkstra's Algorithm?

Dijkstra's Algorithm is a greedy graph algorithm used to find the shortest paths from one starting vertex to all other reachable vertices in a weighted graph with non-negative edge weights.

Why Do We Need Dijkstra's Algorithm?

Dijkstra's Algorithm in Data Structure with Example

Suppose you want to travel from City A to City B. One road has weight 4, but another route through City C has a total weight of 3.

Dijkstra's Algorithm helps us find this shortest route without checking every possible route manually.

Vertex A point in a graph, such as a city.
Edge Weight The distance, time or cost of a connection.
Source The starting vertex from which we calculate distances.

What Is a Greedy Algorithm?

A greedy algorithm makes the best available choice at each step. Dijkstra selects the unvisited vertex with the smallest current distance.

Important: Dijkstra's Algorithm works for graphs with non-negative edge weights. Negative weights are not supported by the standard greedy method.

Tentative and Final Distance

A tentative distance is the shortest distance found so far. It may improve later. A final distance is confirmed when its vertex is selected as the nearest unvisited vertex.

Dijkstra's Algorithm Example with Weighted Graph

We have six vertices: A, B, C, D, E and F. Our starting vertex is A. Every arrow has a weight, and we need to find the shortest routes from A.

4 2 1 5 8 10 2 6 3 A B C D E F
Figure 1: Weighted directed graph. Each arrow represents a connection and its weight.

A direct route from A to B has weight 4. But travelling through C gives a cost of 2 + 1 = 3. This is why we need to check indirect routes.

Step-by-Step Working of Dijkstra's Algorithm

Initially, the distance of A is 0. All other distances are considered infinity. In the table, INF means infinity or no known route yet.

Step 1: Select A (0) A to B costs 4 and A to C costs 2. Set B = 4 and C = 2.
Step 2: Select C (2) C is the nearest unvisited vertex. Through C, B improves from 4 to 3. D becomes 10 and E becomes 12.
Step 3: Select B (3) B to D has weight 5. The new distance to D becomes 3 + 5 = 8. This improves the previous value 10.
Step 4: Select D (8) Through D, E improves to 10. The first route to F gives a distance of 14.
Step 5: Select E (10) Through E, F improves from 14 to 13.
Step 6: Select F (13) All reachable vertices have their final distances.

Complete Distance Table

StageAB CDEF
Initial0INFINFINFINFINF
After A042INFINFINF
After C0321012INF
After B032812INF
After D03281014
After E03281013
After F03281013

On mobile, swipe the table sideways to see all columns.

How Are Distances Updated?

Updating a distance is called relaxation. We compare the old distance with the distance obtained through the current vertex.

newDistance = min(oldDistance, currentDistance + weight)

Example: The old distance to B is 4. Through C, it becomes 2 + 1 = 3. Since 3 is smaller than 4, we update B to 3.

Interactive Dijkstra's Algorithm Visualizer

Click Next Step to watch the algorithm. Green arrows show the best-known shortest-path connections, and orange highlights the active vertex.

Dijkstra from source A Stage 0 of 6
4 2 1 5 8 10 2 6 3 A B C D E F
A0
BINF
CINF
DINF
EINF
FINF

Ready to Begin

Press Next Step to process the first vertex.

Final Shortest Distances and Routes

VertexDistanceShortest Route
A0A
B3A to C to B
C2A to C
D8A to C to B to D
E10A to C to B to D to E
F13A to C to B to D to E to F
Final Answer

The shortest path from A to F is A to C to B to D to E to F. The total cost is 13.

Dijkstra's Algorithm Pseudocode

Set distance[source] = 0
Set all other distances = infinity

Mark all vertices as unvisited

Repeat:
    Select unvisited vertex u
    with the smallest distance

    Mark u as visited

    For each outgoing edge u to v:
        newDistance = distance[u] + weight

        If newDistance is smaller:
            Update distance[v]
            Set parent[v] = u

Stop when no reachable unvisited vertex remains

How Does This Algorithm Work?

First, we select the nearest unvisited vertex. Then we try to improve the distances to its neighbours. We continue until every reachable vertex has its shortest distance confirmed.

Dijkstra's Algorithm in C

This C program uses the same six-vertex graph. It calculates shortest distances and prints the shortest route to every reachable vertex.

#include <stdio.h>
#include <limits.h>

#define N 6
#define INF (INT_MAX / 4)

void printPath(const int parent[N], int vertex) {
    if (parent[vertex] != -1) {
        printPath(parent, parent[vertex]);
        printf(" -> ");
    }
    printf("%c", 'A' + vertex);
}

void dijkstra(int graph[N][N], int source) {
    int dist[N], parent[N], settled[N] = {0};

    for (int i = 0; i < N; i++) {
        dist[i] = INF;
        parent[i] = -1;
    }

    dist[source] = 0;

    for (int step = 0; step < N; step++) {
        int u = -1;

        for (int i = 0; i < N; i++) {
            if (!settled[i] &&
                (u == -1 || dist[i] < dist[u])) {
                u = i;
            }
        }

        if (u == -1 || dist[u] == INF) break;
        settled[u] = 1;

        for (int v = 0; v < N; v++) {
            if (!settled[v] &&
                graph[u][v] != INF &&
                dist[u] + graph[u][v] < dist[v]) {

                dist[v] = dist[u] + graph[u][v];
                parent[v] = u;
            }
        }
    }

    printf("Source: %c\n", 'A' + source);
    printf("Vertex  Distance  Shortest Path\n");

    for (int v = 0; v < N; v++) {
        if (dist[v] == INF) {
            printf("%c       INF       Unreachable\n",
                   'A' + v);
        } else {
            printf("%c       %-8d  ", 'A' + v, dist[v]);
            printPath(parent, v);
            printf("\n");
        }
    }
}

int main(void) {
    int graph[N][N];

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            graph[i][j] = (i == j) ? 0 : INF;
        }
    }

    graph[0][1] = 4;
    graph[0][2] = 2;
    graph[2][1] = 1;
    graph[1][3] = 5;
    graph[2][3] = 8;
    graph[2][4] = 10;
    graph[3][4] = 2;
    graph[3][5] = 6;
    graph[4][5] = 3;

    dijkstra(graph, 0);
    return 0;
}

Output

Source: A
Vertex  Distance  Shortest Path
A       0         A
B       3         A -> C -> B
C       2         A -> C
D       8         A -> C -> B -> D
E       10        A -> C -> B -> D -> E
F       13        A -> C -> B -> D -> E -> F

Explanation of the C Program

  1. The graph is stored using an adjacency matrix.
  2. The distance array stores the shortest known distances.
  3. The settled array tells which vertices have final distances.
  4. The parent array helps us print the shortest routes.
  5. The algorithm selects the nearest unvisited vertex.
  6. It updates neighbouring distances when a shorter route is found.

Time and Space Complexity

Implementation Time Space
Adjacency Matrix O(V²) O(V²)
Adjacency List + Binary Heap O((V + E) log V) O(V + E)

Here, V means the total number of vertices, while E means the total number of edges. For an adjacency-matrix implementation like our C program, the time complexity is O(V²).

Applications of Dijkstra's Algorithm

  • Finding shortest road routes in navigation systems.
  • Network routing between computers.
  • Finding minimum-cost paths in games.
  • Planning efficient delivery routes from one location.

Important Exam Questions

2 Marks: Define Dijkstra's Algorithm.

Dijkstra's Algorithm is a greedy algorithm used to find shortest paths from a source vertex to all reachable vertices in a graph with non-negative edge weights.

5 Marks: Explain Dijkstra's Algorithm with Example.

Dijkstra starts with a source distance of 0 and all other distances as infinity. It repeatedly selects the nearest unvisited vertex and updates its neighbours. In our example, the final shortest distances are 0, 3, 2, 8, 10 and 13 for A to F.

10 Marks: How to Write the Complete Answer.

Write the definition, algorithm steps, weighted graph, complete distance table, final shortest-path result, C program and time complexity.

Frequently Asked Questions

Does Dijkstra work with negative weights?

No. The standard algorithm requires non-negative edge weights.

Can Dijkstra work on directed graphs?

Yes. It works with directed and undirected weighted graphs.

What is the time complexity of Dijkstra?

O(V²) with the simple adjacency-matrix implementation.

What happens when a vertex is unreachable?

Its distance remains infinity because no route exists from the source.

Quick Revision and Conclusion

Dijkstra = Start at source → Choose nearest unvisited → Update distances → Repeat.

In our example, the shortest route from A to F has a total weight of 13. Understanding the relaxation step and practising the distance table will make the algorithm much easier for semester exams.

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Join Telegram Exam updates and free resources