2079 12

BIT152 ยท 2079 ยท 5 marks

Write the Dijkstra's algorithm to find the shortest path between two nodes in graph.

Write the Dijkstra's algorithm to find the shortest path between two nodes in graph. [5]

Discrete StructureChapter 9: Trees and Graph AlgorithmsDijkstra's algorithm for shortest paths

Quick answer

Dijkstra's algorithm is a greedy algorithm that finds the shortest path from a source node to all other nodes (or a specific destination node) in a weighted graph with non-negative edge weights.

Dijkstra's Algorithm for Shortest Path

Definition


Algorithm Steps

DIJKSTRA(Graph G, source s):

1. Initialize:
   - dist[s] = 0          (distance to source is 0)
   - dist[v] = โˆž          (distance to all other vertices is infinity)
   - prev[v] = NULL        (previous node in optimal path)
   - Q = set of all vertices (unvisited set / priority queue)

2. While Q is not empty:
   a. u = vertex in Q with minimum dist[u]   (extract-min)
   b. Remove u from Q
   c. For each neighbor v of u (still in Q):
      - alt = dist[u] + weight(u, v)
      - If alt < dist[v]:
          dist[v] = alt        (relaxation step)
          prev[v] = u

3. Return dist[], prev[]

Pseudocode (Formal)

function Dijkstra(G, s):
    for each vertex v in G:
        dist[v] โ† โˆž
        prev[v] โ† UNDEFINED
    dist[s] โ† 0
    Q โ† all vertices of G

    while Q โ‰  โˆ…:
        u โ† vertex in Q with min dist[u]
        remove u from Q

        for each neighbor v of u:
            if v โˆˆ Q:
                alt โ† dist[u] + w(u, v)
                if alt < dist[v]:
                    dist[v] โ† alt
                    prev[v] โ† u

    return dist[], prev[]

Worked Example

Consider the graph:

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

Find shortest path from A to E.

StepVisiteddist[A]dist[B]dist[C]dist[D]dist[E]
Init-0โˆžโˆžโˆžโˆž
1A042โˆžโˆž
2C04257
3B04257
4D04257
5E04257

Shortest path: A โ†’ C โ†’ D โ†’ E with cost = 7


Key Properties

PropertyDetail
Time ComplexityO(Vยฒ) with array; O((V+E) log V) with min-heap
Space ComplexityO(V)
ConditionEdge weights must be non-negative
TypeGreedy algorithm

Important Notes

  • The relaxation step (if alt < dist[v]) is the core operation
  • Dijkstra's algorithm fails with negative weight edges (use Bellman-Ford instead)
  • It produces a shortest path tree rooted at the source node

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.