100% FREE Updated: Mar 2026 Graph Theory Graph Algorithms

Shortest Path Algorithms

Comprehensive study notes on Shortest Path Algorithms for CMI M.Sc. and Ph.D. Computer Science preparation. This chapter covers key concepts, formulas, and examples needed for your exam.

Shortest Path Algorithms

This chapter rigorously examines fundamental shortest path algorithms, a cornerstone of graph theory with broad applications in network routing and resource optimization. Mastery of these techniques, particularly Dijkstra's algorithm and unweighted path finding, is crucial for solving complex computational problems frequently encountered in advanced computer science examinations.

---

Chapter Contents

|

| Topic |

|---|-------| | 1 | Unweighted Shortest Path | | 2 | Dijkstra's Algorithm |

---

We begin with Unweighted Shortest Path.

Part 1: Unweighted Shortest Path

We explore unweighted shortest paths in graphs, a fundamental concept in graph theory with applications in network routing and resource allocation. For CMI, understanding path properties and algorithmic approaches is critical.

---

Core Concepts

1. Definition and Properties of Unweighted Shortest Paths

An unweighted shortest path between two vertices ss and tt in a graph G=(V,E)G=(V,E) is a path containing the minimum number of edges. The length of this path, denoted d(s,t)d(s,t), is the shortest distance between ss and tt.

📖 Shortest Path Length

The shortest path length d(s,t)d(s,t) between vertices ss and tt is the minimum number of edges in any path connecting ss and tt. If no path exists, d(s,t)=d(s,t) = \infty.

We observe that any subpath of a shortest path is also a shortest path. This is a fundamental optimality principle.

Worked Example: Finding Shortest Path Length

Consider the graph G=(V,E)G=(V,E) where V={A,B,C,D,E,F}V=\{A,B,C,D,E,F\} and E={{A,B},{A,C},{B,D},{C,D},{C,E},{D,F},{E,F}}E=\{\{A,B\}, \{A,C\}, \{B,D\}, \{C,D\}, \{C,E\}, \{D,F\}, \{E,F\}\}. We find the shortest path length from AA to FF.

Step 1: Identify paths from AA to FF.

> Path 1: ABDFA-B-D-F, length 3.
> Path 2: ACDFA-C-D-F, length 3.
> Path 3: ACEFA-C-E-F, length 3.

Step 2: Determine the minimum length.

The minimum length among all paths is 3.

Answer: d(A,F)=3d(A,F) = 3.

:::question type="MCQ" question="Given a graph with vertices V={1,2,3,4,5,6}V=\{1,2,3,4,5,6\} and edges E={{1,2},{1,3},{2,4},{3,4},{3,5},{4,6},{5,6}}E=\{\{1,2\}, \{1,3\}, \{2,4\}, \{3,4\}, \{3,5\}, \{4,6\}, \{5,6\}\}. What is the shortest path length from vertex 1 to vertex 6?" options=["2","3","4","5"] answer="3" hint="Trace paths from vertex 1 to vertex 6, counting edges for each path." solution="We list paths from 1 to 6 and their lengths:

  • 12461-2-4-6 (length 3)

  • 13461-3-4-6 (length 3)

  • 13561-3-5-6 (length 3)

  • The minimum length is 3.
    "
    :::

    ---

    2. Breadth-First Search (BFS) for Unweighted Shortest Paths

    Breadth-First Search (BFS) is an algorithm that systematically explores a graph layer by layer from a starting vertex ss. It inherently finds shortest paths in unweighted graphs because it discovers all vertices at distance kk from ss before discovering any vertices at distance k+1k+1.

    :::algorithm title="BFS for Shortest Paths"

  • Initialize d(s,v)=d(s,v) = \infty for all vVv \in V, d(s,s)=0d(s,s) = 0.

  • Create a queue QQ and enqueue ss.

  • While QQ is not empty:

  • a. Dequeue a vertex uu.
    b. For each neighbor vv of uu:
    i. If d(s,v)=d(s,v) = \infty (i.e., vv is unvisited):
    Set d(s,v)=d(s,u)+1d(s,v) = d(s,u) + 1.
    Enqueue vv.
    :::

    Worked Example: BFS Trace for Shortest Distances

    Consider the graph from the previous example: V={A,B,C,D,E,F}V=\{A,B,C,D,E,F\} and E={{A,B},{A,C},{B,D},{C,D},{C,E},{D,F},{E,F}}E=\{\{A,B\}, \{A,C\}, \{B,D\}, \{C,D\}, \{C,E\}, \{D,F\}, \{E,F\}\}. We use BFS to find shortest path lengths from AA to all other vertices.

    Step 1: Initialization.

    > d(A,A)=0d(A,A)=0, d(A,B)=d(A,B)=\infty, d(A,C)=d(A,C)=\infty, d(A,D)=d(A,D)=\infty, d(A,E)=d(A,E)=\infty, d(A,F)=d(A,F)=\infty.
    > Q=[A]Q=[A]

    Step 2: Dequeue AA. Neighbors of AA are B,CB, C.

    > d(A,B)=d(A,A)+1=1d(A,B) = d(A,A)+1 = 1. Enqueue BB.
    > d(A,C)=d(A,A)+1=1d(A,C) = d(A,A)+1 = 1. Enqueue CC.
    > Q=[B,C]Q=[B,C]

    Step 3: Dequeue BB. Neighbors of BB are A,DA, D. AA is visited.

    > d(A,D)=d(A,B)+1=2d(A,D) = d(A,B)+1 = 2. Enqueue DD.
    > Q=[C,D]Q=[C,D]

    Step 4: Dequeue CC. Neighbors of CC are A,D,EA, D, E. AA is visited. DD is visited (d(A,D)=2d(A,D)=2).

    > d(A,E)=d(A,C)+1=2d(A,E) = d(A,C)+1 = 2. Enqueue EE.
    > Q=[D,E]Q=[D,E]

    Step 5: Dequeue DD. Neighbors of DD are B,C,FB, C, F. B,CB, C are visited.

    > d(A,F)=d(A,D)+1=3d(A,F) = d(A,D)+1 = 3. Enqueue FF.
    > Q=[E,F]Q=[E,F]

    Step 6: Dequeue EE. Neighbors of EE are C,FC, F. C,FC, F are visited.

    > Q=[F]Q=[F]

    Step 7: Dequeue FF. Neighbors of FF are D,ED, E. D,ED, E are visited.

    > Q=[]Q=[]

    Answer: Shortest distances from AA: d(A,A)=0,d(A,B)=1,d(A,C)=1,d(A,D)=2,d(A,E)=2,d(A,F)=3d(A,A)=0, d(A,B)=1, d(A,C)=1, d(A,D)=2, d(A,E)=2, d(A,F)=3.

    :::question type="NAT" question="In a graph with vertices V={1,2,3,4,5}V=\{1,2,3,4,5\} and edges E={{1,2},{1,3},{2,4},{3,4},{4,5}}E=\{\{1,2\}, \{1,3\}, \{2,4\}, \{3,4\}, \{4,5\}\}, what is the shortest path length from vertex 1 to vertex 5 using BFS?" answer="3" hint="Perform a BFS starting from vertex 1. The distance to vertex 5 will be the number of edges in the shortest path." solution="
    Step 1: Initialize distances and queue.
    > d(1,1)=0d(1,1)=0, Q=[1]Q=[1]
    Step 2: Dequeue 1. Neighbors: 2, 3.
    > d(1,2)=1d(1,2)=1, Q=[2]Q=[2]
    > d(1,3)=1d(1,3)=1, Q=[2,3]Q=[2,3]
    Step 3: Dequeue 2. Neighbor: 4 (1 visited).
    > d(1,4)=2d(1,4)=2, Q=[3,4]Q=[3,4]
    Step 4: Dequeue 3. Neighbor: 4 (1 visited, 4 visited with d(1,4)=2d(1,4)=2).
    > Q=[4]Q=[4]
    Step 5: Dequeue 4. Neighbor: 5 (2, 3 visited).
    > d(1,5)=3d(1,5)=3, Q=[5]Q=[5]
    Step 6: Dequeue 5. No unvisited neighbors.
    > Q=[]Q=[]
    The shortest path length from 1 to 5 is 3.
    "
    :::

    ---

    3. Properties of Shortest Path Distances

    For any two adjacent vertices u,vu, v in an unweighted graph, their shortest path distances from a source ss must be closely related.

    📐 Shortest Path Edge Property

    For any edge (u,v)E(u,v) \in E and a source vertex ss, the shortest path distances satisfy:

    d(s,u)d(s,v)1|d(s,u) - d(s,v)| \le 1

    Where: d(s,u)d(s,u) is the shortest distance from ss to uu, and d(s,v)d(s,v) is the shortest distance from ss to vv.
    When to use: Analyzing relationships between distances of adjacent vertices. This property is crucial for proofs related to shortest paths.

    This property implies that for an edge (u,v)(u,v), either d(s,v)=d(s,u)d(s,v) = d(s,u), d(s,v)=d(s,u)+1d(s,v) = d(s,u)+1, or d(s,v)=d(s,u)1d(s,v) = d(s,u)-1. It cannot be that d(s,v)=d(s,u)+2d(s,v) = d(s,u)+2 or d(s,v)=d(s,u)2d(s,v) = d(s,u)-2, because if d(s,v)=d(s,u)+2d(s,v) = d(s,u)+2, we could form a shorter path to vv via uu of length d(s,u)+1d(s,u)+1.

    Worked Example: Applying Shortest Path Edge Property

    Consider a graph where d(s,u)=5d(s,u)=5. We examine possible values for d(s,v)d(s,v) if (u,v)(u,v) is an edge.

    Step 1: Apply the formula.

    >

    d(s,u)d(s,v)1|d(s,u) - d(s,v)| \le 1

    >
    5d(s,v)1|5 - d(s,v)| \le 1

    Step 2: Solve for d(s,v)d(s,v).

    >

    15d(s,v)1-1 \le 5 - d(s,v) \le 1

    >
    15d(s,v)15-1 - 5 \le -d(s,v) \le 1 - 5

    >
    6d(s,v)4-6 \le -d(s,v) \le -4

    >
    4d(s,v)64 \le d(s,v) \le 6

    Answer: If d(s,u)=5d(s,u)=5 and (u,v)(u,v) is an edge, then d(s,v)d(s,v) must be 4, 5, or 6.

    :::question type="MSQ" question="Let G=(V,E)G=(V,E) be an unweighted graph and ss be a source vertex. For an edge (u,v)E(u,v) \in E, which of the following statements about d(s,u)d(s,u) and d(s,v)d(s,v) are always true?" options=["d(s,u)d(s,v)+2d(s,u) \ne d(s,v)+2","d(s,u)=d(s,v)d(s,u) = d(s,v) implies u,vu,v are in the same BFS layer","d(s,u)d(s,v)1|d(s,u) - d(s,v)| \le 1","d(s,u)d(s,v)1d(s,u) \ge d(s,v)-1"] answer="Option 1,Option 3,Option 4" hint="Recall the definition of shortest path distance and how it relates to adjacent vertices. If d(s,u)=kd(s,u) = k, then d(s,v)d(s,v) can be k1,k,k-1, k, or k+1k+1." solution="

  • d(s,u)d(s,v)+2d(s,u) \ne d(s,v)+2: If d(s,u)=d(s,v)+2d(s,u) = d(s,v)+2, it implies d(s,v)=d(s,u)2d(s,v) = d(s,u)-2. Then a path from ss to uu could be formed by taking the shortest path to vv and then traversing edge (v,u)(v,u), resulting in a path of length d(s,v)+1=(d(s,u)2)+1=d(s,u)1d(s,v)+1 = (d(s,u)-2)+1 = d(s,u)-1, which contradicts d(s,u)d(s,u) being the shortest path length. So this statement is true.

  • d(s,u)=d(s,v)d(s,u) = d(s,v) implies u,vu,v are in the same BFS layer: While uu and vv are in the same BFS layer if their distances from ss are equal, the statement 'implies' means it's a direct consequence. This is true by definition of BFS layers.

  • d(s,u)d(s,v)1|d(s,u) - d(s,v)| \le 1: This is the fundamental shortest path edge property. It is always true.

  • d(s,u)d(s,v)1d(s,u) \ge d(s,v)-1: This is equivalent to d(s,v)d(s,u)1d(s,v) - d(s,u) \le 1, which is part of d(s,u)d(s,v)1|d(s,u) - d(s,v)| \le 1. So this is always true.

  • "
    :::

    ---

    Advanced Applications

    1. Degree Sum on Shortest Paths

    Consider a shortest path PP between ss and tt. Vertices not on PP have specific constraints on how many neighbors they can have on PP. This property is critical for proving bounds on the sum of degrees of vertices on a shortest path.

    Vertex Adjacency to Shortest Path

    Let P=v0v1vkP = v_0 v_1 \cdots v_k be a shortest path from v0v_0 to vkv_k. For any vertex xV(P)x \notin V(P), xx can be adjacent to at most two vertices vi,vjv_i, v_j on PP such that ji+2j \ge i+2. More generally, xx can be adjacent to at most three vertices of PP to avoid creating a shorter path. If xx is adjacent to vi,vj,vl,vmv_i, v_j, v_l, v_m where i<j<l<mi < j < l < m, then at least two pairs (vi,vj)(v_i, v_j) or (vl,vm)(v_l, v_m) must have a path distance 3\ge 3 along PP. For example, if ji+3j \ge i+3, then replacing vivjv_i \dots v_j with vixvjv_i - x - v_j would shorten the path.

    This property is a stronger form of the argument from the CMI PYQ. The PYQ statement says "if xx were adjacent to four vertices of PP, then two of them would be at distance at least 33 along PP, and replacing that subpath by a two-edge route through xx would give a shorter sts-t path". This implies xx can be adjacent to at most 3 vertices of PP.

    Worked Example: Illustrating the Adjacency Constraint

    Let P=v0v1v2v3v4P = v_0 - v_1 - v_2 - v_3 - v_4 be a shortest path. Consider a vertex xV(P)x \notin V(P).

    Step 1: Assume xx is adjacent to v0v_0 and v3v_3.

    > If xx is adjacent to v0v_0 and v3v_3, we can form a path v0xv3v_0 - x - v_3.
    > The length of v0xv3v_0 - x - v_3 is 2.
    > The length of v0v1v2v3v_0 - v_1 - v_2 - v_3 (subpath of PP) is 3.
    > Since 2<32 < 3, replacing v0v1v2v3v_0 - v_1 - v_2 - v_3 with v0xv3v_0 - x - v_3 would create a shorter path from v0v_0 to v3v_3, contradicting PP being a shortest path.

    Step 2: Conclude the constraint.

    A vertex xV(P)x \notin V(P) cannot be adjacent to viv_i and vjv_j if ij3|i-j| \ge 3. This means xx can connect to viv_i and vjv_j only if ij2|i-j| \le 2.

    Answer: If xV(P)x \notin V(P), it can be adjacent to vi,vi+1v_i, v_{i+1} (distance 1 along PP), vi,vi+2v_i, v_{i+2} (distance 2 along PP), or a single viv_i. It cannot connect to vi,vi+3v_i, v_{i+3} or further apart. This implies xx can be adjacent to at most 3 vertices on PP (e.g., vi,vi+1,vi+2v_i, v_{i+1}, v_{i+2}). If it connects to 4 vertices, say vi,vj,vk,vlv_i, v_j, v_k, v_l, then at least two must be separated by distance 3\ge 3 on PP, creating a shortcut.

    :::question type="MCQ" question="Let P=v0v1vkP = v_0 v_1 \cdots v_k be a shortest path in an unweighted graph GG. Consider a vertex xV(P)x \notin V(P). If xx is adjacent to viv_i and vjv_j where i<ji < j, which of the following conditions must be true for PP to remain a shortest path?" options=["ji1j - i \le 1","ji2j - i \le 2","ji3j - i \le 3","jikj - i \le k"] answer="ji2j - i \le 2" hint="If ji3j-i \ge 3, then the path segment vivjv_i \dots v_j has length jij-i. Could you create a shorter path using xx?" solution="
    If ji3j-i \ge 3, then the subpath vivjv_i \dots v_j has length jij-i. If xx is adjacent to both viv_i and vjv_j, we could replace the subpath vivjv_i \dots v_j with vixvjv_i - x - v_j, which has length 2.
    For PP to be a shortest path, this replacement must not create a shorter path. Thus, the length of vivjv_i \dots v_j must be less than or equal to 2.
    So, ji2j-i \le 2.
    If ji=0j-i=0, i=ji=j, not two distinct vertices.
    If ji=1j-i=1, vi,vi+1v_i, v_{i+1} are adjacent on PP. Path length 1. 121 \le 2. Valid.
    If ji=2j-i=2, vi,vi+1,vi+2v_i, v_{i+1}, v_{i+2}. Path length 2. 222 \le 2. Valid.
    If ji=3j-i=3, vi,vi+1,vi+2,vi+3v_i, v_{i+1}, v_{i+2}, v_{i+3}. Path length 3. If xx connects viv_i and vi+3v_{i+3}, then vixvi+3v_i - x - v_{i+3} has length 2, which is shorter than 3. This contradicts PP being a shortest path.
    Therefore, ji2j-i \le 2.
    "
    :::

    ---

    Problem-Solving Strategies

    💡 BFS for Unweighted Shortest Paths

    Always consider BFS for unweighted shortest path problems. Its layer-by-layer exploration guarantees finding the minimum number of edges. If you need to reconstruct the path, store predecessors during BFS.

    💡 Proof by Contradiction for Shortest Path Properties

    Many proofs involving shortest paths (like the degree sum bound) rely on contradiction. Assume a property (e.g., a path is shorter, or a vertex connects to too many path vertices) and show it leads to a contradiction with the definition of a shortest path.

    ---

    Common Mistakes

    ⚠️ BFS vs. DFS

    ❌ Using Depth-First Search (DFS) for shortest paths in unweighted graphs. DFS explores deeply before broadly, so it does not guarantee finding the shortest path.
    ✅ Always use BFS for unweighted shortest path problems. DFS is for connectivity, cycle detection, etc.

    ⚠️ Forgetting Unweighted

    ❌ Applying algorithms like Dijkstra's without considering if edge weights are involved. For unweighted graphs, BFS is simpler and more efficient than Dijkstra's algorithm.
    ✅ For unweighted graphs, BFS is the optimal choice. Dijkstra's is for non-negative weighted graphs.

    ---

    Practice Questions

    :::question type="NAT" question="Consider a complete graph KnK_n with n2n \ge 2 vertices. What is the shortest path length between any two distinct vertices?" answer="1" hint="In a complete graph, every pair of distinct vertices is connected by an edge." solution="In a complete graph KnK_n, by definition, every pair of distinct vertices is connected by an edge. Therefore, the shortest path between any two distinct vertices has length 1."
    :::

    :::question type="MCQ" question="Let GG be a connected unweighted graph. If d(s,v)d(s,v) is the shortest path length from a source ss to vertex vv, and uu is a neighbor of vv, which of the following is NOT a possible value for d(s,u)d(s,u)?" options=["d(s,v)1d(s,v)-1","d(s,v)d(s,v)","d(s,v)+1d(s,v)+1","d(s,v)+2d(s,v)+2"] answer="d(s,v)+2d(s,v)+2" hint="Recall the shortest path edge property d(s,u)d(s,v)1|d(s,u) - d(s,v)| \le 1." solution="The shortest path edge property states that for any edge (u,v)(u,v), d(s,u)d(s,v)1|d(s,u) - d(s,v)| \le 1. This implies that d(s,u)d(s,u) can be d(s,v)1d(s,v)-1, d(s,v)d(s,v), or d(s,v)+1d(s,v)+1. It cannot be d(s,v)+2d(s,v)+2, because if it were, we could form a path from ss to uu of length d(s,v)+1d(s,v)+1 by taking the shortest path to vv and then traversing the edge (v,u)(v,u), which is shorter than d(s,v)+2d(s,v)+2, contradicting the definition of d(s,u)d(s,u) as the shortest path length."
    :::

    :::question type="MSQ" question="Let P=v0v1vkP = v_0 v_1 \cdots v_k be a shortest path from s=v0s=v_0 to t=vkt=v_k in an unweighted graph GG. Which of the following statements are necessarily true?" options=["Every subpath vivi+1vjv_i v_{i+1} \cdots v_j of PP is also a shortest path from viv_i to vjv_j.","If xV(P)x \notin V(P) is adjacent to viv_i and vjv_j (i<ji<j), then ji2j-i \le 2.","The sum of degrees vV(P)deg(v)\sum_{v \in V(P)} \deg(v) is always less than or equal to 2V(P)2|V(P)|.","If GG is a tree, then PP is the unique path between ss and tt."] answer="Every subpath vivi+1vjv_i v_{i+1} \cdots v_j of PP is also a shortest path from viv_i to vj,Ifv_j,If x \notin V(P)isadjacenttois adjacent to v_i andand v_j (( i),then), then j-i \le 2,If,If G isatree,thenis a tree, then P istheuniquepathbetweenis the unique path between s andand t "hint="Considerthedefinitionsandpropertiesdiscussed.Forthedegreesum,considertheedgeswithin" hint="Consider the definitions and properties discussed. For the degree sum, consider the edges within P andedgesconnectingtoand edges connecting to V(G) \setminus V(P)$. For uniqueness, recall properties of trees." solution="

  • Every subpath vivi+1vjv_i v_{i+1} \cdots v_j of PP is also a shortest path from viv_i to vjv_j.: This is a fundamental property of shortest paths. If there were a shorter path from viv_i to vjv_j, we could replace the subpath of PP with it, making PP shorter, which is a contradiction. So, this is true.

  • If xV(P)x \notin V(P) is adjacent to viv_i and vjv_j (i<ji<j), then ji2j-i \le 2.: As demonstrated in the advanced example, if ji3j-i \ge 3, then replacing the subpath vivjv_i \dots v_j with vixvjv_i - x - v_j (length 2) would create a shorter path, contradicting PP being a shortest path. So, this is true.

  • The sum of degrees vV(P)deg(v)\sum_{v \in V(P)} \deg(v) is always less than or equal to 2V(P)2|V(P)|.: This is not necessarily true. Consider a star graph where the center is on a shortest path. Its degree can be n1n-1, which can be much larger than 2V(P)2|V(P)| if V(P)|V(P)| is small. The PYQ proved vV(P)deg(v)3n\sum_{v \in V(P)} \deg(v) \le 3n, not 2V(P)2|V(P)|. So, this is false.

  • If GG is a tree, then PP is the unique path between ss and tt.: In any tree, there is a unique path between any two distinct vertices. Since PP is a path between ss and tt, it must be that unique path. So, this is true.

  • "
    :::

    :::question type="NAT" question="Consider an m×nm \times n grid graph. What is the shortest path length from the top-left vertex (1,1)(1,1) to the bottom-right vertex (m,n)(m,n)?" answer="m+n-2" hint="Movement is restricted to adjacent cells (up, down, left, right). The shortest path involves only moving right and down." solution="To move from (1,1)(1,1) to (m,n)(m,n) in an m×nm \times n grid graph, we need to make (m1)(m-1) moves downwards and (n1)(n-1) moves to the right. Each move corresponds to one edge. The total number of moves (edges) in any shortest path is (m1)+(n1)=m+n2(m-1) + (n-1) = m+n-2."
    :::

    :::question type="MCQ" question="Let GG be a connected graph with nn vertices. Let PP be a shortest path from ss to tt. The maximum length of PP can be at most:" options=["n1n-1","nn","2n12n-1","n2n^2"] answer="n1n-1" hint="A simple path in a graph with nn vertices can visit each vertex at most once. What is the maximum number of edges in such a path?" solution="A path is a sequence of distinct vertices. In a graph with nn vertices, a simple path can have at most nn vertices. If a path has nn vertices, it has n1n-1 edges. This forms a Hamiltonian path. Since a shortest path cannot revisit vertices, its length is bounded by n1n-1. For example, a path graph PnP_n has nn vertices and a shortest path between its endpoints has length n1n-1."
    :::

    ---

    Summary

    Key Formulas & Takeaways

    |

    | Formula/Concept | Expression |

    |---|----------------|------------| | 1 | Shortest Path Length | d(s,t)=min(edges in Ps,t)d(s,t) = \min(\text{edges in } P_{s,t}) | | 2 | BFS for Unweighted SP | Layered exploration from source ss | | 3 | Shortest Path Edge Property | d(s,u)d(s,v)1for (u,v)E|d(s,u) - d(s,v)| \le 1 \quad \text{for } (u,v) \in E | | 4 | Subpath Optimality | Subpaths of SP are also SPs | | 5 | Vertex Adjacency to SP | xV(P)x \notin V(P) adjacent to vi,vjV(P)    ij2v_i, v_j \in V(P) \implies |i-j| \le 2 |

    ---

    What's Next?

    💡 Continue Learning

    This topic connects to:

      • Weighted Shortest Path: Algorithms like Dijkstra's and Bellman-Ford extend shortest path concepts to graphs with edge weights.

      • All-Pairs Shortest Path: Algorithms like Floyd-Warshall and Johnson's compute shortest paths between all pairs of vertices.

      • Network Flow: Shortest path algorithms are often subroutines in more complex network flow problems.

    ---

    💡 Next Up

    Proceeding to Dijkstra's Algorithm.

    ---

    Part 2: Dijkstra's Algorithm

    Dijkstra's algorithm is a fundamental graph algorithm for finding the shortest paths from a single source vertex to all other vertices in a weighted graph with non-negative edge weights. We apply this algorithm to solve various shortest path problems in network routing, transportation, and resource allocation.

    ---

    Core Concepts

    1. Shortest Path Definition

    The shortest path between two vertices in a weighted graph is a path where the sum of the weights of its constituent edges is minimized. Dijkstra's algorithm determines these paths from a designated source vertex.

    📐 Path Weight

    Let P=(v0,v1,,vk)P = (v_0, v_1, \dots, v_k) be a path from v0v_0 to vkv_k. The weight of the path W(P)W(P) is given by:

    W(P)=i=0k1w(vi,vi+1)W(P) = \sum_{i=0}^{k-1} w(v_i, v_{i+1})

    Where: w(vi,vi+1)w(v_i, v_{i+1}) is the weight of the edge connecting viv_i and vi+1v_{i+1}.
    When to use: To calculate the total cost or distance of a specific path in a weighted graph.

    Worked Example:

    Consider a graph with vertices A,B,C,DA, B, C, D and edges (A,B)(A,B) with weight 33, (B,C)(B,C) with weight 22, (A,D)(A,D) with weight 77, and (D,C)(D,C) with weight 11. We want to find the weight of the path ADCA \to D \to C.

    Step 1: Identify the edges in the path.

    > The path ADCA \to D \to C consists of edges (A,D)(A,D) and (D,C)(D,C).

    Step 2: Sum the weights of the edges.

    >

    W(ADC)=w(A,D)+w(D,C)W(A \to D \to C) = w(A,D) + w(D,C)

    >
    W(ADC)=7+1W(A \to D \to C) = 7 + 1

    >
    W(ADC)=8W(A \to D \to C) = 8

    Answer: The weight of the path ADCA \to D \to C is 88.

    :::question type="MCQ" question="Given a graph with edges E={(S,A,2),(S,B,5),(A,C,1),(B,C,3),(C,D,4)}E = \{(S,A,2), (S,B,5), (A,C,1), (B,C,3), (C,D,4)\}, where (u,v,w)(u,v,w) denotes an edge from uu to vv with weight ww. What is the weight of the path SBCDS \to B \to C \to D?" options=["7","8","9","12"] answer="12" hint="Sum the weights of the edges along the specified path." solution="Step 1: Identify the edges in the path SBCDS \to B \to C \to D.
    > The edges are (S,B)(S,B), (B,C)(B,C), and (C,D)(C,D).

    Step 2: Sum the weights of these edges.
    >

    W(SBCD)=w(S,B)+w(B,C)+w(C,D)W(S \to B \to C \to D) = w(S,B) + w(B,C) + w(C,D)

    >
    W(SBCD)=5+3+4W(S \to B \to C \to D) = 5 + 3 + 4

    >
    W(SBCD)=12W(S \to B \to C \to D) = 12

    The weight of the path is 1212."
    :::

    ---

    2. Algorithm Overview

    Dijkstra's algorithm is a greedy algorithm that iteratively finds the shortest paths from a source vertex ss to all other vertices in a graph. It maintains a set of visited vertices for which the shortest path has been finalized and a distance estimate for all other vertices.

    Key Characteristics
      • Greedy Approach: At each step, it selects the unvisited vertex with the smallest current distance estimate from the source.
      • Non-negative Edge Weights: It requires all edge weights to be non-negative.
      • Single-Source: Computes shortest paths from one specific source vertex to all other vertices.

    Worked Example:

    Consider a graph with vertices A,B,C,DA, B, C, D and edges (A,B,1)(A,B,1), (A,C,4)(A,C,4), (B,C,2)(B,C,2), (B,D,5)(B,D,5), (C,D,1)(C,D,1). We want to find the shortest path from source AA to all other vertices. We will illustrate the first few steps of the greedy selection.

    Step 1: Initialize distances and set AA as the source.

    > dist(A)=0dist(A)=0, dist(B)=dist(B)=\infty, dist(C)=dist(C)=\infty, dist(D)=dist(D)=\infty.
    > Priority Queue PQ={(0,A)}PQ = \{(0, A)\}.

    Step 2: Extract minimum from PQPQ.

    > We extract (0,A)(0, A). AA is now visited.

    Step 3: Relax neighbors of AA.

    > For neighbor BB: dist(B)=min(,dist(A)+w(A,B))=min(,0+1)=1dist(B) = \min(\infty, dist(A) + w(A,B)) = \min(\infty, 0+1) = 1. Add (1,B)(1, B) to PQPQ.
    > For neighbor CC: dist(C)=min(,dist(A)+w(A,C))=min(,0+4)=4dist(C) = \min(\infty, dist(A) + w(A,C)) = \min(\infty, 0+4) = 4. Add (4,C)(4, C) to PQPQ.
    > PQ={(1,B),(4,C)}PQ = \{(1, B), (4, C)\}.

    Step 4: Extract minimum from PQPQ.

    > We extract (1,B)(1, B). BB is now visited.

    Step 5: Relax neighbors of BB.

    > For neighbor CC: dist(C)=min(4,dist(B)+w(B,C))=min(4,1+2)=3dist(C) = \min(4, dist(B) + w(B,C)) = \min(4, 1+2) = 3. Update (4,C)(4, C) to (3,C)(3, C) in PQPQ.
    > For neighbor DD: dist(D)=min(,dist(B)+w(B,D))=min(,1+5)=6dist(D) = \min(\infty, dist(B) + w(B,D)) = \min(\infty, 1+5) = 6. Add (6,D)(6, D) to PQPQ.
    > PQ={(3,C),(6,D)}PQ = \{(3, C), (6, D)\}.

    Answer: After these steps, the current shortest distance estimates are dist(A)=0,dist(B)=1,dist(C)=3,dist(D)=6dist(A)=0, dist(B)=1, dist(C)=3, dist(D)=6. The next vertex to be processed would be CC.

    :::question type="MCQ" question="In Dijkstra's algorithm, what is the primary criterion used to select the next vertex to add to the set of finalized shortest paths?" options=["The vertex with the most outgoing edges","The vertex with the highest degree","The unvisited vertex with the smallest current distance estimate from the source","A randomly chosen unvisited vertex"] answer="The unvisited vertex with the smallest current distance estimate from the source" hint="Recall the greedy nature of Dijkstra's algorithm." solution="Explanation: Dijkstra's algorithm is a greedy algorithm. It always selects the unvisited vertex that has the smallest current shortest distance estimate from the source vertex. This ensures that the shortest path to that vertex has been found and can then be used to update distances to its neighbors."
    :::

    ---

    3. Algorithm Steps and Relaxation

    Dijkstra's algorithm proceeds in phases, maintaining a distance array `dist` and a predecessor array `prev`. The core operation is `relax(u, v, w)`, which attempts to improve the shortest path estimate to vv by going through uu.

    Initialization:

  • Set dist[s]=0dist[s] = 0 for the source vertex ss, and dist[v]=dist[v] = \infty for all other vertices vsv \ne s.

  • Initialize prev[v]=nullprev[v] = \operatorname{null} for all vv.

  • Create a min-priority queue PQPQ and insert (0,s)(0, s).
  • Main Loop:

  • While PQPQ is not empty:

  • a. Extract vertex uu with the minimum dist[u]dist[u] from PQPQ.
    b. If uu has already been visited (its shortest path finalized), continue.
    c. Mark uu as visited.
    d. For each neighbor vv of uu:
    i. Perform `relax(u, v, w(u,v))`.

    📐 Relaxation Operation

    Given an edge (u,v)(u,v) with weight w(u,v)w(u,v):
    If dist[u]+w(u,v)<dist[v]dist[u] + w(u,v) < dist[v], then update:

    dist[v]=dist[u]+w(u,v)dist[v] = dist[u] + w(u,v)

    prev[v]=uprev[v] = u

    Insert or update (dist[v],v)(dist[v], v) in the priority queue.
    Where: dist[x]dist[x] is the current shortest distance estimate from the source to xx, w(u,v)w(u,v) is the weight of the edge (u,v)(u,v).
    When to use: This is the core update step in Dijkstra's, Bellman-Ford, and Floyd-Warshall algorithms.

    Worked Example:

    Consider the graph from the previous example: vertices A,B,C,DA, B, C, D and edges (A,B,1)(A,B,1), (A,C,4)(A,C,4), (B,C,2)(B,C,2), (B,D,5)(B,D,5), (C,D,1)(C,D,1). Source is AA. We trace the full algorithm.

    Step 1: Initialization

    > dist={A:0,B:,C:,D:}dist = \{A:0, B:\infty, C:\infty, D:\infty\}
    > prev={A:null,B:null,C:null,D:null}prev = \{A:\operatorname{null}, B:\operatorname{null}, C:\operatorname{null}, D:\operatorname{null}\}
    > PQ={(0,A)}PQ = \{(0, A)\}

    Step 2: Process AA

    > Extract (0,A)(0, A) from PQPQ.
    > Relax neighbors of AA:
    > For BB: dist[A]+w(A,B)=0+1=1<dist[B]dist[A] + w(A,B) = 0+1 = 1 < dist[B]. Update dist[B]=1dist[B]=1, prev[B]=Aprev[B]=A. Add (1,B)(1, B) to PQPQ.
    > For CC: dist[A]+w(A,C)=0+4=4<dist[C]dist[A] + w(A,C) = 0+4 = 4 < dist[C]. Update dist[C]=4dist[C]=4, prev[C]=Aprev[C]=A. Add (4,C)(4, C) to PQPQ.
    > PQ={(1,B),(4,C)}PQ = \{(1, B), (4, C)\}

    Step 3: Process BB

    > Extract (1,B)(1, B) from PQPQ.
    > Relax neighbors of BB:
    > For CC: dist[B]+w(B,C)=1+2=3<dist[C]dist[B] + w(B,C) = 1+2 = 3 < dist[C]. Update dist[C]=3dist[C]=3, prev[C]=Bprev[C]=B. Update (4,C)(4, C) to (3,C)(3, C) in PQPQ.
    > For DD: dist[B]+w(B,D)=1+5=6<dist[D]dist[B] + w(B,D) = 1+5 = 6 < dist[D]. Update dist[D]=6dist[D]=6, prev[D]=Bprev[D]=B. Add (6,D)(6, D) to PQPQ.
    > PQ={(3,C),(6,D)}PQ = \{(3, C), (6, D)\}

    Step 4: Process CC

    > Extract (3,C)(3, C) from PQPQ.
    > Relax neighbors of CC:
    > For DD: dist[C]+w(C,D)=3+1=4<dist[D]dist[C] + w(C,D) = 3+1 = 4 < dist[D]. Update dist[D]=4dist[D]=4, prev[D]=Cprev[D]=C. Update (6,D)(6, D) to (4,D)(4, D) in PQPQ.
    > PQ={(4,D)}PQ = \{(4, D)\}

    Step 5: Process DD

    > Extract (4,D)(4, D) from PQPQ.
    > DD has no unvisited neighbors.
    > PQ={}PQ = \{\}

    Answer: The final shortest distances from AA are: dist(A)=0,dist(B)=1,dist(C)=3,dist(D)=4dist(A)=0, dist(B)=1, dist(C)=3, dist(D)=4. The shortest paths can be reconstructed using prevprev: ABCDA \to B \to C \to D.

    :::question type="NAT" question="Consider a directed graph with vertices S,A,B,CS, A, B, C and edges (S,A,2)(S,A,2), (S,B,6)(S,B,6), (A,C,3)(A,C,3), (B,C,1)(B,C,1), (C,D,4)(C,D,4). Using Dijkstra's algorithm from source SS, what is the shortest distance to vertex DD?" answer="7" hint="Trace Dijkstra's algorithm step-by-step, performing relaxation operations and using a priority queue." solution="Step 1: Initialization
    > dist={S:0,A:,B:,C:,D:}dist = \{S:0, A:\infty, B:\infty, C:\infty, D:\infty\}
    > prev={S:null,A:null,B:null,C:null,D:null}prev = \{S:\operatorname{null}, A:\operatorname{null}, B:\operatorname{null}, C:\operatorname{null}, D:\operatorname{null}\}
    > PQ={(0,S)}PQ = \{(0, S)\}

    Step 2: Process SS
    > Extract (0,S)(0, S).
    > Relax neighbors of SS:
    > For AA: dist[S]+w(S,A)=0+2=2<dist[A]dist[S] + w(S,A) = 0+2 = 2 < dist[A]. dist[A]=2dist[A]=2, prev[A]=Sprev[A]=S. Add (2,A)(2, A) to PQPQ.
    > For BB: dist[S]+w(S,B)=0+6=6<dist[B]dist[S] + w(S,B) = 0+6 = 6 < dist[B]. dist[B]=6dist[B]=6, prev[B]=Sprev[B]=S. Add (6,B)(6, B) to PQPQ.
    > PQ={(2,A),(6,B)}PQ = \{(2, A), (6, B)\}

    Step 3: Process AA
    > Extract (2,A)(2, A).
    > Relax neighbors of AA:
    > For CC: dist[A]+w(A,C)=2+3=5<dist[C]dist[A] + w(A,C) = 2+3 = 5 < dist[C]. dist[C]=5dist[C]=5, prev[C]=Aprev[C]=A. Add (5,C)(5, C) to PQPQ.
    > PQ={(5,C),(6,B)}PQ = \{(5, C), (6, B)\} (order might vary based on tie-breaking for equal priorities)

    Step 4: Process CC
    > Extract (5,C)(5, C).
    > Relax neighbors of CC:
    > For DD: dist[C]+w(C,D)=5+4=9<dist[D]dist[C] + w(C,D) = 5+4 = 9 < dist[D]. dist[D]=9dist[D]=9, prev[D]=Cprev[D]=C. Add (9,D)(9, D) to PQPQ.
    > PQ={(6,B),(9,D)}PQ = \{(6, B), (9, D)\}

    Step 5: Process BB
    > Extract (6,B)(6, B).
    > Relax neighbors of BB:
    > For CC: dist[B]+w(B,C)=6+1=7dist[B] + w(B,C) = 6+1 = 7. dist[C]dist[C] is currently 55. Since 757 \not< 5, no update.
    > PQ={(9,D)}PQ = \{(9, D)\}

    Step 6: Process DD
    > Extract (9,D)(9, D).
    > DD has no neighbors.
    > PQ={}PQ = \{\}

    Answer: The final shortest distance to DD is 99. Oh, wait, I made a mistake in the trace. Let's re-evaluate the edge (B,C,1)(B,C,1).

    Let's re-trace focusing on the priority queue and relaxation:

    Step 1: Initialization
    > dist={S:0,A:,B:,C:,D:}dist = \{S:0, A:\infty, B:\infty, C:\infty, D:\infty\}
    > PQ={(0,S)}PQ = \{(0, S)\}

    Step 2: Process SS
    > Extract (0,S)(0, S).
    > Neighbors of SS: A,BA, B.
    > dist[A]=min(,dist[S]+w(S,A))=min(,0+2)=2dist[A] = \min(\infty, dist[S]+w(S,A)) = \min(\infty, 0+2) = 2. Push (2,A)(2, A) to PQPQ.
    > dist[B]=min(,dist[S]+w(S,B))=min(,0+6)=6dist[B] = \min(\infty, dist[S]+w(S,B)) = \min(\infty, 0+6) = 6. Push (6,B)(6, B) to PQPQ.
    > PQ={(2,A),(6,B)}PQ = \{(2, A), (6, B)\}

    Step 3: Process AA
    > Extract (2,A)(2, A).
    > Neighbors of AA: CC.
    > dist[C]=min(,dist[A]+w(A,C))=min(,2+3)=5dist[C] = \min(\infty, dist[A]+w(A,C)) = \min(\infty, 2+3) = 5. Push (5,C)(5, C) to PQPQ.
    > PQ={(5,C),(6,B)}PQ = \{(5, C), (6, B)\}

    Step 4: Process CC
    > Extract (5,C)(5, C).
    > Neighbors of CC: DD.
    > dist[D]=min(,dist[C]+w(C,D))=min(,5+4)=9dist[D] = \min(\infty, dist[C]+w(C,D)) = \min(\infty, 5+4) = 9. Push (9,D)(9, D) to PQPQ.
    > PQ={(6,B),(9,D)}PQ = \{(6, B), (9, D)\}

    Step 5: Process BB
    > Extract (6,B)(6, B).
    > Neighbors of BB: CC.
    > dist[C]=min(5,dist[B]+w(B,C))=min(5,6+1)=min(5,7)=5dist[C] = \min(5, dist[B]+w(B,C)) = \min(5, 6+1) = \min(5, 7) = 5. No change to dist[C]dist[C].
    > PQ={(9,D)}PQ = \{(9, D)\}

    Step 6: Process DD
    > Extract (9,D)(9, D).
    > DD has no neighbors.
    > PQ={}PQ = \{\}

    The shortest distance to DD is 99. The question states `(C,D,4)`.
    Okay, I need to be extremely careful with my own example graph. Let me re-read the question's graph definition.
    Vertices S,A,B,CS, A, B, C. Edges (S,A,2)(S,A,2), (S,B,6)(S,B,6), (A,C,3)(A,C,3), (B,C,1)(B,C,1), (C,D,4)(C,D,4).
    The vertex DD is mentioned in (C,D,4)(C,D,4) but not in the list of vertices S,A,B,CS,A,B,C. This implies DD is also a vertex.

    The path SACDS \to A \to C \to D has weight 2+3+4=92+3+4 = 9.
    The path SBCDS \to B \to C \to D has weight 6+1+4=116+1+4 = 11.

    My trace is correct, the shortest distance to D is 9.
    The expected answer is 7. This means my question's graph or expected answer is inconsistent.

    Let's modify the graph for the question to match the intended answer 7.
    If DD is 7, it means some path is shorter.
    SBCDS \to B \to C \to D gives 6+1+4=116+1+4=11.
    SACDS \to A \to C \to D gives 2+3+4=92+3+4=9.

    To get 7, maybe an edge (S,D)(S,D) with weight 7, or a different intermediate path.
    Let's change the question graph to allow for a distance of 7.
    E.g., if (A,D)(A,D) existed with weight 5, then SADS \to A \to D would be 2+5=72+5=7.
    Or if (B,D)(B,D) existed with weight 1, then SBDS \to B \to D would be 6+1=76+1=7.

    Let's use a simpler graph to ensure correctness.
    Vertices S,A,B,TS, A, B, T. Edges (S,A,3)(S,A,3), (S,B,1)(S,B,1), (A,T,2)(A,T,2), (B,T,5)(B,T,5). Shortest path to TT?
    SBTS \to B \to T: 1+5=61+5=6.
    SATS \to A \to T: 3+2=53+2=5.
    Answer should be 5.

    Let's take a new example for the NAT question.
    Vertices S,A,B,CS, A, B, C. Edges (S,A,2),(S,B,1),(A,C,3),(B,C,5)(S,A,2), (S,B,1), (A,C,3), (B,C,5). From SS to CC.

  • dist={S:0,A:,B:,C:}dist = \{S:0, A:\infty, B:\infty, C:\infty\}, PQ={(0,S)}PQ = \{(0,S)\}

  • Pop SS. dist[A]=min(,0+2)=2dist[A]=\min(\infty, 0+2)=2. dist[B]=min(,0+1)=1dist[B]=\min(\infty, 0+1)=1. PQ={(1,B),(2,A)}PQ = \{(1,B), (2,A)\}

  • Pop BB. dist[C]=min(,1+5)=6dist[C]=\min(\infty, 1+5)=6. PQ={(2,A),(6,C)}PQ = \{(2,A), (6,C)\}

  • Pop AA. dist[C]=min(6,2+3)=5dist[C]=\min(6, 2+3)=5. PQ={(5,C)}PQ = \{(5,C)\}

  • Pop CC. Done.

  • Shortest distance to CC is 5.

    This is a better graph. I need to update the question.

    :::question type="NAT" question="Consider a directed graph with vertices S,A,B,CS, A, B, C and edges (S,A,2)(S,A,2), (S,B,1)(S,B,1), (A,C,3)(A,C,3), (B,C,5)(B,C,5). Using Dijkstra's algorithm from source SS, what is the shortest distance to vertex CC?" answer="5" hint="Trace Dijkstra's algorithm step-by-step, performing relaxation operations and using a priority queue." solution="Step 1: Initialization
    > dist={S:0,A:,B:,C:}dist = \{S:0, A:\infty, B:\infty, C:\infty\}
    > PQ={(0,S)}PQ = \{(0, S)\}

    Step 2: Process SS
    > Extract (0,S)(0, S).
    > Relax neighbors of SS:
    > For AA: dist[S]+w(S,A)=0+2=2<dist[A]dist[S] + w(S,A) = 0+2 = 2 < dist[A]. dist[A]=2dist[A]=2. Push (2,A)(2, A) to PQPQ.
    > For BB: dist[S]+w(S,B)=0+1=1<dist[B]dist[S] + w(S,B) = 0+1 = 1 < dist[B]. dist[B]=1dist[B]=1. Push (1,B)(1, B) to PQPQ.
    > PQ={(1,B),(2,A)}PQ = \{(1, B), (2, A)\}

    Step 3: Process BB
    > Extract (1,B)(1, B).
    > Relax neighbors of BB:
    > For CC: dist[B]+w(B,C)=1+5=6<dist[C]dist[B] + w(B,C) = 1+5 = 6 < dist[C]. dist[C]=6dist[C]=6. Push (6,C)(6, C) to PQPQ.
    > PQ={(2,A),(6,C)}PQ = \{(2, A), (6, C)\}

    Step 4: Process AA
    > Extract (2,A)(2, A).
    > Relax neighbors of AA:
    > For CC: dist[A]+w(A,C)=2+3=5<dist[C]dist[A] + w(A,C) = 2+3 = 5 < dist[C]. dist[C]=5dist[C]=5. Update (6,C)(6, C) to (5,C)(5, C) in PQPQ.
    > PQ={(5,C)}PQ = \{(5, C)\}

    Step 5: Process CC
    > Extract (5,C)(5, C).
    > CC has no neighbors.
    > PQ={}PQ = \{\}

    The shortest distance to CC is 55."
    :::

    ---

    4. Non-negative Edge Weights Constraint

    Dijkstra's algorithm is only guaranteed to find the correct shortest paths if all edge weights in the graph are non-negative. If negative edge weights are present, Dijkstra's algorithm may produce incorrect results.

    ⚠️ Negative Edge Weights

    ❌ Dijkstra's algorithm fails with negative edge weights. It makes a greedy decision based on current shortest paths, which might be suboptimal if a negative cycle or a path with negative edges could later reduce a finalized distance.
    ✅ For graphs with negative edge weights (but no negative cycles), use the Bellman-Ford algorithm. For all-pairs shortest paths with negative weights, use the Floyd-Warshall algorithm.

    Worked Example:

    Consider a graph with vertices S,A,BS, A, B and edges (S,A,1)(S,A,1), (A,B,1)(A,B,1), (S,B,4)(S,B,4), (B,A,3)(B,A,-3). Source is SS.

    Step 1: Initialization

    > dist={S:0,A:,B:}dist = \{S:0, A:\infty, B:\infty\}
    > PQ={(0,S)}PQ = \{(0, S)\}

    Step 2: Process SS

    > Extract (0,S)(0, S).
    > Relax neighbors of SS:
    > For AA: dist[A]=min(,0+1)=1dist[A] = \min(\infty, 0+1) = 1. Add (1,A)(1, A) to PQPQ.
    > For BB: dist[B]=min(,0+4)=4dist[B] = \min(\infty, 0+4) = 4. Add (4,B)(4, B) to PQPQ.
    > PQ={(1,A),(4,B)}PQ = \{(1, A), (4, B)\}

    Step 3: Process AA

    > Extract (1,A)(1, A).
    > Relax neighbors of AA:
    > For BB: dist[B]=min(4,dist[A]+w(A,B))=min(4,1+1)=2dist[B] = \min(4, dist[A]+w(A,B)) = \min(4, 1+1) = 2. Update (4,B)(4, B) to (2,B)(2, B) in PQPQ.
    > PQ={(2,B)}PQ = \{(2, B)\}

    Step 4: Process BB

    > Extract (2,B)(2, B).
    > Relax neighbors of BB:
    > For AA: dist[A]=min(1,dist[B]+w(B,A))=min(1,2+(3))=min(1,1)dist[A] = \min(1, dist[B]+w(B,A)) = \min(1, 2+(-3)) = \min(1, -1).
    > Since 1<1-1 < 1, dist[A]dist[A] should be updated to 1-1. However, AA has already been extracted and marked as visited. Dijkstra's algorithm does not re-process visited vertices.
    > PQ={}PQ = \{\}

    Answer: Dijkstra's algorithm reports dist(A)=1dist(A)=1 and dist(B)=2dist(B)=2. The true shortest path to AA is SBAS \to B \to A with weight 4+(3)=14+(-3)=1. The true shortest path to BB is SBS \to B with weight 44. The algorithm failed to find the true shortest path to AA because AA was finalized before a shorter path through BB was discovered.

    :::question type="MCQ" question="Which of the following scenarios would cause Dijkstra's algorithm to fail to find the correct shortest paths?" options=["The graph is undirected.","The graph contains a cycle with positive edge weights.","The graph contains an edge with a weight of zero.","The graph contains an edge with a negative weight."] answer="The graph contains an edge with a negative weight." hint="Recall the fundamental assumption Dijkstra's algorithm makes about edge weights." solution="Explanation: Dijkstra's algorithm relies on the assumption that once a vertex is extracted from the priority queue, its shortest path distance is final. This assumption holds true only if all edge weights are non-negative. A negative edge weight can lead to a situation where a path through an already 'finalized' vertex becomes shorter later, which Dijkstra's cannot correctly handle."
    :::

    ---

    5. Properties of Shortest Paths

    Shortest paths possess several important properties, crucial for understanding graph algorithms.

    Triangle Inequality

    For any three vertices x,u,vx, u, v in a graph, the shortest path distance from xx to vv is less than or equal to the sum of the shortest path distance from xx to uu and the weight of the edge (u,v)(u,v).

    d(x,v)d(x,u)+w(u,v)d(x,v) \le d(x,u) + w(u,v)

    This property is fundamental to the correctness of relaxation-based algorithms like Dijkstra's and Bellman-Ford.

    Worked Example:

    Let d(x,y)d(x,y) denote the shortest path distance from vertex xx to vertex yy. Suppose in a graph with positive edge weights, d(S,A)=10d(S,A) = 10 and d(S,B)=18d(S,B) = 18. If there is an edge (A,B)(A,B) with weight w(A,B)w(A,B), what can we infer about w(A,B)w(A,B)?

    Step 1: Apply the triangle inequality.

    > We know that the shortest path from SS to BB cannot be longer than the path that goes from SS to AA and then directly to BB.
    >

    d(S,B)d(S,A)+w(A,B)d(S,B) \le d(S,A) + w(A,B)

    Step 2: Substitute the given values.

    >

    1810+w(A,B)18 \le 10 + w(A,B)

    Step 3: Solve for w(A,B)w(A,B).

    >

    1810w(A,B)18 - 10 \le w(A,B)

    >
    8w(A,B)8 \le w(A,B)

    Answer: The weight of the edge w(A,B)w(A,B) must be greater than or equal to 88.

    :::question type="MSQ" question="Let GG be a directed graph with distinct and non-negative edge weights. Let ss be a starting vertex and tt a destination vertex. Assume that GG has at least one ss-tt path. Which of the following statements are always true?" options=["Every shortest ss-tt path must include the minimum-weight edge of GG.","Every shortest ss-tt path must exclude the maximum-weight edge of GG.","If d(s,u)d(s,u) and d(s,v)d(s,v) are shortest path distances from ss to uu and vv respectively, and (u,v)(u,v) is an edge with weight w(u,v)w(u,v), then d(s,v)d(s,u)+w(u,v)d(s,v) \le d(s,u) + w(u,v).","A shortest ss-tt path does not contain any cycles."] answer="If d(s,u)d(s,u) and d(s,v)d(s,v) are shortest path distances from ss to uu and vv respectively, and (u,v)(u,v) is an edge with weight w(u,v)w(u,v), then d(s,v)d(s,u)+w(u,v).d(s,v) \le d(s,u) + w(u,v).,A shortest ss-tt path does not contain any cycles." hint="Consider counterexamples for the first two statements. The last two statements relate to fundamental properties of shortest paths." solution="Explanation:

    • 'Every shortest ss-tt path must include the minimum-weight edge of GG.' (False)

    Consider a graph with vertices s,A,t,X,Ys, A, t, X, Y. Edges: (s,A,10)(s,A,10), (A,t,10)(A,t,10), (X,Y,1)(X,Y,1). The minimum weight edge is (X,Y)(X,Y) with weight 1. A shortest ss-tt path (sAts \to A \to t, total weight 20) does not necessarily use the minimum-weight edge.
    • 'Every shortest ss-tt path must exclude the maximum-weight edge of GG.' (False)

    Consider a graph with vertices s,t,As, t, A. Edges: (s,t,100)(s,t,100), (s,A,1)(s,A,1), (A,t,1)(A,t,1). The maximum weight edge is (s,t)(s,t) with weight 100. If the only path from ss to tt is sts \to t, then the shortest path must include the maximum-weight edge. Even if there's another path sAts \to A \to t (weight 2), if the max edge is w(A,t)=1w(A,t)=1, and w(s,A)=1w(s,A)=1, and w(s,t)=100w(s,t)=100, the max edge is (s,t)(s,t) and it's not part of the shortest path. But what if the max edge is part of the shortest path? E.g., sts \to t with weight 10. Max edge in graph is 10. Shortest path uses it.
    • 'If d(s,u)d(s,u) and d(s,v)d(s,v) are shortest path distances from ss to uu and vv respectively, and (u,v)(u,v) is an edge with weight w(u,v)w(u,v), then d(s,v)d(s,u)+w(u,v)d(s,v) \le d(s,u) + w(u,v).' (True)

    This is the triangle inequality for shortest paths. The shortest path from ss to vv cannot be longer than any path from ss to vv, including the path that first goes from ss to uu via a shortest path and then takes the direct edge (u,v)(u,v).
    • 'A shortest ss-tt path does not contain any cycles.' (True)

    If a shortest path contained a cycle, say P=(s,,x,,x,,t)P = (s, \dots, x, \dots, x, \dots, t), and all edge weights are non-negative, then removing the cycle (x,,x)(x, \dots, x) would result in a path with a weight less than or equal to W(P)W(P) (strictly less if the cycle has positive total weight). This contradicts the assumption that PP is a shortest path. If there are zero-weight edges, removing a zero-weight cycle would result in a path of equal weight, which is still a shortest path, but the statement 'does not contain any cycles' still holds for a shortest path. For distinct edge weights, it would be strictly shorter."
    :::

    ---

    Advanced Applications

    Dijkstra's algorithm is foundational. Understanding its properties allows us to solve problems that extend beyond simple shortest path computations.

    Worked Example:

    Consider a country with NN cities and MM one-way roads. Each road has a travel time (weight). We want to find the fastest route from a source city SS to a destination city DD, but we are allowed to take a single flight (which has a fixed cost FF) from any city UU to any other city VV, provided there's no direct road from UU to VV. If there is a direct road, a flight is not allowed between UU and VV.

    Step 1: Model the problem as a graph.

    > We can create a 'layered' graph. Create two copies of the original graph, G1G_1 and G2G_2.
    > G1G_1: Represents the state 'no flight taken yet'.
    > G2G_2: Represents the state 'one flight has been taken'.
    > Vertices in G1G_1 are viv_i, vertices in G2G_2 are viv_i'.

    Step 2: Add edges to the layered graph.

    > For every original road (U,V)(U,V) with weight ww, add edges (U,V)(U,V) in G1G_1 with weight ww, and (U,V)(U',V') in G2G_2 with weight ww.
    > For every pair of cities (U,V)(U,V) where there is NO direct road in the original graph, add an edge (U,V)(U,V') from G1G_1 to G2G_2 with weight FF. This represents taking the flight.

    Step 3: Run Dijkstra's algorithm.

    > Run Dijkstra's algorithm from the source SS (in G1G_1, i.e., SG1S_{G_1}).
    > The shortest path to DG1D_{G_1} would be the shortest path without any flight.
    > The shortest path to DG2D_{G_2} would be the shortest path using exactly one flight.
    > The overall fastest route is min(d(SG1,DG1),d(SG1,DG2))\min(d(S_{G_1}, D_{G_1}), d(S_{G_1}, D_{G_2})).

    Answer: By constructing a layered graph that encodes the state of having taken a flight or not, we can use standard Dijkstra's algorithm to find the optimal path.

    :::question type="NAT" question="A delivery drone needs to travel from a warehouse (source SS) to a customer (destination DD) in a city. The city map is a directed graph with NN intersections and MM one-way streets, each with a travel time in minutes (positive integer weights). The drone can carry a single battery pack and use it once to instantly warp from any intersection UU to any other intersection VV (even if there's a street between them). This warp takes WW minutes, regardless of distance. What is the minimum travel time from SS to DD if the drone can use the warp at most once? Assume N=5N=5, M=6M=6, W=10W=10. The graph edges are: (S,A,5),(S,B,2),(A,C,3),(B,C,1),(C,D,4),(A,D,12)(S,A,5), (S,B,2), (A,C,3), (B,C,1), (C,D,4), (A,D,12). Calculate the shortest time from SS to DD with at most one warp." answer="7" hint="Create a layered graph. One layer for 'no warp used', another for 'warp used'. Add warp edges between layers. Then run Dijkstra." solution="Step 1: Construct the layered graph.
    > Create two copies of the graph: G0G_0 (no warp used) and G1G_1 (warp used).
    > Vertices in G0G_0: S0,A0,B0,C0,D0S_0, A_0, B_0, C_0, D_0.
    > Vertices in G1G_1: S1,A1,B1,C1,D1S_1, A_1, B_1, C_1, D_1.

    Step 2: Add edges within layers.
    > For each original edge (u,v,w)(u,v,w):
    > Add (u0,v0,w)(u_0, v_0, w) to G0G_0.
    > Add (u1,v1,w)(u_1, v_1, w) to G1G_1.
    > Edges: (S0,A0,5),(S0,B0,2),(A0,C0,3),(B0,C0,1),(C0,D0,4),(A0,D0,12)(S_0,A_0,5), (S_0,B_0,2), (A_0,C_0,3), (B_0,C_0,1), (C_0,D_0,4), (A_0,D_0,12)
    > And similar for G1G_1.

    Step 3: Add warp edges between layers.
    > For every pair of vertices (U,V)(U,V) in the original graph, add an edge (U0,V1,W)(U_0, V_1, W) (warp cost).
    > Warp edges (cost 10):
    > (S0,A1,10),(S0,B1,10),(S0,C1,10),(S0,D1,10)(S_0,A_1,10), (S_0,B_1,10), (S_0,C_1,10), (S_0,D_1,10)
    > (A0,S1,10),(A0,B1,10),(A0,C1,10),(A0,D1,10)(A_0,S_1,10), (A_0,B_1,10), (A_0,C_1,10), (A_0,D_1,10)
    > etc.

    Step 4: Run Dijkstra's from S0S_0.
    > We are interested in d(S0,D0)d(S_0, D_0) and d(S0,D1)d(S_0, D_1). The minimum of these will be the answer.

    Trace Dijkstra's from S0S_0:
    > Initial dist(S0)=0dist(S_0)=0, all others \infty.
    > PQ={(0,S0)}PQ = \{(0, S_0)\}

    > Pop (0,S0)(0, S_0):
    > dist(A0)=min(,0+5)=5dist(A_0) = \min(\infty, 0+5) = 5. Push (5,A0)(5, A_0).
    > dist(B0)=min(,0+2)=2dist(B_0) = \min(\infty, 0+2) = 2. Push (2,B0)(2, B_0).
    > Warp from S0S_0:
    > dist(A1)=min(,0+10)=10dist(A_1) = \min(\infty, 0+10) = 10. Push (10,A1)(10, A_1).
    > dist(B1)=min(,0+10)=10dist(B_1) = \min(\infty, 0+10) = 10. Push (10,B1)(10, B_1).
    > dist(C1)=min(,0+10)=10dist(C_1) = \min(\infty, 0+10) = 10. Push (10,C1)(10, C_1).
    > dist(D1)=min(,0+10)=10dist(D_1) = \min(\infty, 0+10) = 10. Push (10,D1)(10, D_1).
    > PQ={(2,B0),(5,A0),(10,A1),(10,B1),(10,C1),(10,D1)}PQ = \{(2, B_0), (5, A_0), (10, A_1), (10, B_1), (10, C_1), (10, D_1)\}

    > Pop (2,B0)(2, B_0):
    > dist(C0)=min(,2+1)=3dist(C_0) = \min(\infty, 2+1) = 3. Push (3,C0)(3, C_0).
    > Warp from B0B_0:
    > dist(S1)=min(,2+10)=12dist(S_1) = \min(\infty, 2+10) = 12. Push (12,S1)(12, S_1).
    > dist(A1)=min(10,2+10)=10dist(A_1) = \min(10, 2+10) = 10. No change.
    > dist(C1)=min(10,2+10)=10dist(C_1) = \min(10, 2+10) = 10. No change.
    > dist(D1)=min(10,2+10)=10dist(D_1) = \min(10, 2+10) = 10. No change.
    > PQ={(3,C0),(5,A0),(10,A1),(10,B1),(10,C1),(10,D1),(12,S1)}PQ = \{(3, C_0), (5, A_0), (10, A_1), (10, B_1), (10, C_1), (10, D_1), (12, S_1)\}

    > Pop (3,C0)(3, C_0):
    > dist(D0)=min(,3+4)=7dist(D_0) = \min(\infty, 3+4) = 7. Push (7,D0)(7, D_0).
    > Warp from C0C_0:
    > dist(S1)=min(12,3+10)=12dist(S_1) = \min(12, 3+10) = 12. No change.
    > dist(A1)=min(10,3+10)=10dist(A_1) = \min(10, 3+10) = 10. No change.
    > dist(B1)=min(10,3+10)=10dist(B_1) = \min(10, 3+10) = 10. No change.
    > dist(D1)=min(10,3+10)=10dist(D_1) = \min(10, 3+10) = 10. No change.
    > PQ={(5,A0),(7,D0),(10,A1),(10,B1),(10,C1),(10,D1),(12,S1)}PQ = \{(5, A_0), (7, D_0), (10, A_1), (10, B_1), (10, C_1), (10, D_1), (12, S_1)\}

    > Pop (5,A0)(5, A_0):
    > dist(C0)=min(3,5+3)=3dist(C_0) = \min(3, 5+3) = 3. No change.
    > dist(D0)=min(7,5+12)=7dist(D_0) = \min(7, 5+12) = 7. No change.
    > Warp from A0A_0:
    > dist(S1)=min(12,5+10)=12dist(S_1) = \min(12, 5+10) = 12. No change.
    > dist(B1)=min(10,5+10)=10dist(B_1) = \min(10, 5+10) = 10. No change.
    > dist(C1)=min(10,5+10)=10dist(C_1) = \min(10, 5+10) = 10. No change.
    > dist(D1)=min(10,5+10)=10dist(D_1) = \min(10, 5+10) = 10. No change.
    > PQ={(7,D0),}PQ = \{(7, D_0), \dots\}

    > Pop (7,D0)(7, D_0):
    > Shortest path to D0D_0 is 7.

    > At this point, we have found a path to D0D_0 with cost 7. We also have dist(D1)=10dist(D_1)=10 from S0D1S_0 \to D_1 (direct warp).
    > The shortest path to DD is min(dist(D0),dist(D1))=min(7,10)=7\min(dist(D_0), dist(D_1)) = \min(7, 10) = 7.

    Answer: The minimum travel time from SS to DD is 77."
    :::

    ---

    Problem-Solving Strategies

    💡 Tracing Dijkstra's

    When tracing Dijkstra's algorithm, maintain a table of current shortest distances `dist[v]` and predecessors `prev[v]` for all vertices vv. Use a min-priority queue to keep track of unvisited vertices and their current `dist` values. Always extract the minimum distance vertex from the priority queue and then relax its neighbors.

    💡 Graph Transformation

    Many problems that seem more complex than simple shortest path can be transformed into a standard shortest path problem on a modified graph. This often involves creating "layered" graphs, where each layer represents a state (e.g., number of items collected, number of special abilities used).

    ---

    Common Mistakes

    ⚠️ Incorrectly Handling Negative Weights

    ❌ Applying Dijkstra's algorithm directly to graphs containing negative edge weights.
    ✅ For graphs with negative edge weights, use Bellman-Ford (for single source) or Floyd-Warshall (for all pairs). Dijkstra's correctness relies on the assumption that adding an edge always increases or maintains path length.

    ⚠️ Ignoring Graph Type

    ❌ Using Dijkstra's for undirected graphs without converting edges or for graphs where edge weights are not applicable.
    ✅ For undirected graphs, treat each undirected edge (u,v)(u,v) with weight ww as two directed edges (u,v,w)(u,v,w) and (v,u,w)(v,u,w). Ensure all edge weights are positive.

    ⚠️ Priority Queue Implementation Errors

    ❌ Not updating existing entries in the priority queue efficiently, or adding duplicate entries without proper handling, leading to incorrect or inefficient execution.
    ✅ A good priority queue implementation (e.g., a Fibonacci heap or a binary heap that supports `decrease-key` operations) is crucial for optimal performance. If a simple binary heap is used, it's common to add new entries when distances are updated, and ignore outdated entries when popped (check if popped distance is greater than current `dist[v]`).

    ---

    Practice Questions

    :::question type="MCQ" question="Consider a directed graph with vertices V={A,B,C,D,E}V = \{A, B, C, D, E\} and edges with positive weights: (A,B,2),(A,C,4),(B,C,1),(B,D,7),(C,E,3),(D,E,1)(A,B,2), (A,C,4), (B,C,1), (B,D,7), (C,E,3), (D,E,1). If we run Dijkstra's algorithm starting from vertex AA, what is the shortest distance to vertex EE?" options=["7","8","9","10"] answer="7" hint="Trace Dijkstra's algorithm, keeping track of distances and the priority queue. The path ABCEA \to B \to C \to E is one candidate." solution="Step 1: Initialization
    > dist={A:0,B:,C:,D:,E:}dist = \{A:0, B:\infty, C:\infty, D:\infty, E:\infty\}
    > PQ={(0,A)}PQ = \{(0, A)\}

    Step 2: Process AA
    > Extract (0,A)(0, A).
    > dist[B]=min(,0+2)=2dist[B] = \min(\infty, 0+2) = 2. Push (2,B)(2, B) to PQPQ.
    > dist[C]=min(,0+4)=4dist[C] = \min(\infty, 0+4) = 4. Push (4,C)(4, C) to PQPQ.
    > PQ={(2,B),(4,C)}PQ = \{(2, B), (4, C)\}

    Step 3: Process BB
    > Extract (2,B)(2, B).
    > dist[C]=min(4,2+1)=3dist[C] = \min(4, 2+1) = 3. Update (4,C)(4, C) to (3,C)(3, C) in PQPQ.
    > dist[D]=min(,2+7)=9dist[D] = \min(\infty, 2+7) = 9. Push (9,D)(9, D) to PQPQ.
    > PQ={(3,C),(9,D)}PQ = \{(3, C), (9, D)\}

    Step 4: Process CC
    > Extract (3,C)(3, C).
    > dist[E]=min(,3+3)=6dist[E] = \min(\infty, 3+3) = 6. Push (6,E)(6, E) to PQPQ.
    > PQ={(6,E),(9,D)}PQ = \{(6, E), (9, D)\}

    Step 5: Process EE
    > Extract (6,E)(6, E).
    > EE has no neighbors.
    > The shortest distance to EE is 66.

    Wait, there is an edge (D,E,1)(D,E,1).
    Let's retry the trace carefully.

    Step 1: Initialization
    > dist={A:0,B:,C:,D:,E:}dist = \{A:0, B:\infty, C:\infty, D:\infty, E:\infty\}
    > PQ={(0,A)}PQ = \{(0, A)\}

    Step 2: Process AA
    > Extract (0,A)(0, A).
    > dist[B]=2dist[B] = 2. Add (2,B)(2, B) to PQPQ.
    > dist[C]=4dist[C] = 4. Add (4,C)(4, C) to PQPQ.
    > PQ={(2,B),(4,C)}PQ = \{(2, B), (4, C)\}

    Step 3: Process BB
    > Extract (2,B)(2, B).
    > dist[C]=min(4,2+1)=3dist[C] = \min(4, 2+1) = 3. Update (4,C)(4, C) to (3,C)(3, C) in PQPQ.
    > dist[D]=min(,2+7)=9dist[D] = \min(\infty, 2+7) = 9. Add (9,D)(9, D) to PQPQ.
    > PQ={(3,C),(9,D)}PQ = \{(3, C), (9, D)\}

    Step 4: Process CC
    > Extract (3,C)(3, C).
    > dist[E]=min(,3+3)=6dist[E] = \min(\infty, 3+3) = 6. Add (6,E)(6, E) to PQPQ.
    > PQ={(6,E),(9,D)}PQ = \{(6, E), (9, D)\}

    Step 5: Process EE
    > Extract (6,E)(6, E).
    > EE has no unvisited neighbors.
    > The current shortest distance to EE is 6.

    Let's check the path ABCEA \to B \to C \to E. Weight 2+1+3=62+1+3 = 6.
    Let's check ACEA \to C \to E. Weight 4+3=74+3=7.
    Let's check ABDEA \to B \to D \to E. Weight 2+7+1=102+7+1 = 10.

    The shortest distance to EE is indeed 6. The options provided are 7, 8, 9, 10. This means my question has an issue with the options or the intended answer. I will adjust the question to match option 7.

    Let's change w(C,E)w(C,E) from 3 to 4.
    Then ABCEA \to B \to C \to E would be 2+1+4=72+1+4 = 7.
    And ACEA \to C \to E would be 4+4=84+4 = 8.
    And ABDEA \to B \to D \to E would be 2+7+1=102+7+1 = 10.
    So the shortest path to EE would be 7. This matches one of the options.

    Revised Question:
    Vertices V={A,B,C,D,E}V = \{A, B, C, D, E\} and edges with positive weights: (A,B,2),(A,C,4),(B,C,1),(B,D,7),(C,E,4),(D,E,1)(A,B,2), (A,C,4), (B,C,1), (B,D,7), (C,E,4), (D,E,1). If we run Dijkstra's algorithm starting from vertex AA, what is the shortest distance to vertex EE?

    Revised Solution:
    Step 1: Initialization
    > dist={A:0,B:,C:,D:,E:}dist = \{A:0, B:\infty, C:\infty, D:\infty, E:\infty\}
    > PQ={(0,A)}PQ = \{(0, A)\}

    Step 2: Process AA
    > Extract (0,A)(0, A).
    > dist[B]=2dist[B] = 2. Add (2,B)(2, B) to PQPQ.
    > dist[C]=4dist[C] = 4. Add (4,C)(4, C) to PQPQ.
    > PQ={(2,B),(4,C)}PQ = \{(2, B), (4, C)\}

    Step 3: Process BB
    > Extract (2,B)(2, B).
    > dist[C]=min(4,2+1)=3dist[C] = \min(4, 2+1) = 3. Update (4,C)(4, C) to (3,C)(3, C) in PQPQ.
    > dist[D]=min(,2+7)=9dist[D] = \min(\infty, 2+7) = 9. Add (9,D)(9, D) to PQPQ.
    > PQ={(3,C),(9,D)}PQ = \{(3, C), (9, D)\}

    Step 4: Process CC
    > Extract (3,C)(3, C).
    > dist[E]=min(,3+4)=7dist[E] = \min(\infty, 3+4) = 7. Add (7,E)(7, E) to PQPQ.
    > PQ={(7,E),(9,D)}PQ = \{(7, E), (9, D)\}

    Step 5: Process EE
    > Extract (7,E)(7, E).
    > EE has no unvisited neighbors.
    > The shortest distance to EE is 77.

    Answer: The shortest distance to EE is 77."
    :::

    :::question type="NAT" question="A directed acyclic graph (DAG) has vertices V={S,X,Y,Z,T}V = \{S, X, Y, Z, T\} and edge weights: (S,X,3),(S,Y,2),(X,Z,4),(Y,Z,1),(Y,T,6),(Z,T,2)(S,X,3), (S,Y,2), (X,Z,4), (Y,Z,1), (Y,T,6), (Z,T,2). What is the shortest distance from SS to TT using Dijkstra's algorithm?" answer="5" hint="Follow the steps of Dijkstra's algorithm, processing vertices in increasing order of their shortest path estimates." solution="Step 1: Initialization
    > dist={S:0,X:,Y:,Z:,T:}dist = \{S:0, X:\infty, Y:\infty, Z:\infty, T:\infty\}
    > PQ={(0,S)}PQ = \{(0, S)\}

    Step 2: Process SS
    > Extract (0,S)(0, S).
    > dist[X]=min(,0+3)=3dist[X] = \min(\infty, 0+3) = 3. Push (3,X)(3, X) to PQPQ.
    > dist[Y]=min(,0+2)=2dist[Y] = \min(\infty, 0+2) = 2. Push (2,Y)(2, Y) to PQPQ.
    > PQ={(2,Y),(3,X)}PQ = \{(2, Y), (3, X)\}

    Step 3: Process YY
    > Extract (2,Y)(2, Y).
    > dist[Z]=min(,2+1)=3dist[Z] = \min(\infty, 2+1) = 3. Push (3,Z)(3, Z) to PQPQ.
    > dist[T]=min(,2+6)=8dist[T] = \min(\infty, 2+6) = 8. Push (8,T)(8, T) to PQPQ.
    > PQ={(3,X),(3,Z),(8,T)}PQ = \{(3, X), (3, Z), (8, T)\}

    Step 4: Process XX (or ZZ, tie-breaking doesn't affect final answer)
    > Extract (3,X)(3, X).
    > dist[Z]=min(3,3+4)=3dist[Z] = \min(3, 3+4) = 3. No change.
    > PQ={(3,Z),(8,T)}PQ = \{(3, Z), (8, T)\}

    Step 5: Process ZZ
    > Extract (3,Z)(3, Z).
    > dist[T]=min(8,3+2)=5dist[T] = \min(8, 3+2) = 5. Update (8,T)(8, T) to (5,T)(5, T) in PQPQ.
    > PQ={(5,T)}PQ = \{(5, T)\}

    Step 6: Process TT
    > Extract (5,T)(5, T).
    > TT has no neighbors.
    > The shortest distance to TT is 55.

    Answer: The shortest distance from SS to TT is 55."
    :::

    :::question type="MSQ" question="Which of the following statements are true regarding Dijkstra's algorithm?" options=["It works correctly on graphs with negative edge weights if there are no negative cycles.","Its time complexity is O(ElogV)O(E \log V) using a binary heap priority queue.","It can find shortest paths from a single source to all reachable vertices.","It is a dynamic programming algorithm."] answer="Its time complexity is O(ElogV)O(E \log V) using a binary heap priority queue.,It can find shortest paths from a single source to all reachable vertices." hint="Recall the conditions for Dijkstra's correctness, its purpose, and its typical implementation complexity." solution="Explanation:

    • 'It works correctly on graphs with negative edge weights if there are no negative cycles.' (False)

    Dijkstra's algorithm requires non-negative edge weights. Even without negative cycles, negative edge weights can cause it to fail. For such graphs, Bellman-Ford is used.
    • 'Its time complexity is O(ElogV)O(E \log V) using a binary heap priority queue.' (True)

    With a binary heap, each of the EE edge relaxations can lead to a `decrease-key` operation (or insert), which takes O(logV)O(\log V) time. There are VV `extract-min` operations, each taking O(logV)O(\log V). So, the total complexity is O(VlogV+ElogV)=O((V+E)logV)O(V \log V + E \log V) = O((V+E) \log V), which simplifies to O(ElogV)O(E \log V) for connected graphs where EV1E \ge V-1.
    • 'It can find shortest paths from a single source to all reachable vertices.' (True)

    This is the primary purpose of Dijkstra's algorithm.
    • 'It is a dynamic programming algorithm.' (False)

    Dijkstra's is a greedy algorithm. While some shortest path algorithms (like Bellman-Ford and Floyd-Warshall) use dynamic programming, Dijkstra's makes locally optimal choices to achieve a global optimum."
    :::

    :::question type="MCQ" question="A city map is represented as a graph where intersections are vertices and streets are edges with positive travel times. Due to construction, the travel time of a specific street (u,v)(u,v) is reduced. What is the most efficient way to update the shortest path from a source SS to a destination TT?" options=["Rerun Dijkstra's algorithm from SS to TT on the modified graph.","Run Bellman-Ford algorithm from SS to TT.","The shortest path cannot be shorter, so no update is needed.","Only update the path if SuvTS \to \dots \to u \to v \to \dots \to T was the original shortest path, by reducing its total weight."] answer="Rerun Dijkstra's algorithm from SS to TT on the modified graph." hint="Consider the global impact of a local change on shortest paths." solution="Explanation:

    • 'Rerun Dijkstra's algorithm from SS to TT on the modified graph.' (Correct)

    Reducing an edge weight might create a new shortest path or shorten an existing one that was previously not optimal. The most robust and generally efficient way to find the new shortest path is to rerun Dijkstra's algorithm on the updated graph.
    • 'Run Bellman-Ford algorithm from SS to TT.' (Incorrect)

    Bellman-Ford is unnecessary as edge weights are still positive. Dijkstra's is more efficient for positive weights.
    • 'The shortest path cannot be shorter, so no update is needed.' (Incorrect)

    Reducing an edge weight can definitely make a path shorter, potentially changing the shortest path.
    • 'Only update the path if SuvTS \to \dots \to u \to v \to \dots \to T was the original shortest path, by reducing its total weight.' (Incorrect)

    A different path not involving (u,v)(u,v) might now become the shortest path due to other changes, or a path involving (u,v)(u,v) but not being the original shortest path might become the new shortest path. A local update is insufficient; a full recomputation (or a more complex incremental update algorithm) is needed."
    :::

    ---

    Summary

    Key Formulas & Takeaways

    |

    | Formula/Concept | Expression |

    |---|----------------|------------| | 1 | Path Weight | W(P)=w(ei)W(P) = \sum w(e_i) | | 2 | Relaxation | If dist[u]+w(u,v)<dist[v]dist[u] + w(u,v) < dist[v], then dist[v]=dist[u]+w(u,v)dist[v] = dist[u] + w(u,v) | | 3 | Triangle Inequality | d(x,v)d(x,u)+w(u,v)d(x,v) \le d(x,u) + w(u,v) | | 4 | Time Complexity (Binary Heap) | O(ElogV)O(E \log V) | | 5 | Requirement | Non-negative edge weights | | 6 | Purpose | Single-source shortest paths |

    ---

    What's Next?

    💡 Continue Learning

    This topic connects to:

      • Bellman-Ford Algorithm: Handles graphs with negative edge weights (but no negative cycles). Essential for understanding limitations of Dijkstra's.

      • Floyd-Warshall Algorithm: Computes all-pairs shortest paths, suitable for graphs with negative edge weights (no negative cycles).

      • Prim's Algorithm: Another greedy algorithm, but for finding Minimum Spanning Trees, sharing structural similarities (priority queue usage) with Dijkstra's.

      • A* Search Algorithm: An extension of Dijkstra's that uses a heuristic function to guide its search, making it more efficient for single-pair shortest path problems on large graphs, especially in AI pathfinding.

    Chapter Summary

    Shortest Path Algorithms — Key Points

    Unweighted Shortest Path: Breadth-First Search (BFS) efficiently finds shortest paths in terms of edge count for unweighted graphs, with a time complexity of O(V+E)O(V+E).
    Dijkstra's Algorithm Purpose: Solves the single-source shortest path (SSSP) problem for graphs with non-negative edge weights.
    Core Principle: Dijkstra's algorithm operates on a greedy approach, iteratively selecting the unvisited vertex with the smallest known distance from the source and relaxing its outgoing edges.
    Relaxation Operation: The fundamental step where the distance to a neighbor vv of a vertex uu is updated if a shorter path through uu is found: d[v]=min(d[v],d[u]+w(u,v))d[v] = \min(d[v], d[u] + w(u,v)).
    Priority Queue: A min-priority queue (e.g., binary heap) is critical for efficient selection of the next vertex to process, storing `(distance, vertex)` pairs.
    Time Complexity (Binary Heap): When implemented with a binary min-priority queue, Dijkstra's algorithm has a time complexity of O((V+E)logV)O((V+E)\log V) or O(ElogV)O(E\log V) for dense graphs where EVE \gg V.
    * Limitations: Dijkstra's algorithm fails to produce correct shortest paths in graphs containing negative edge weights due to its greedy nature.

    ---

    Chapter Review Questions

    :::question type="MCQ" question="Which algorithm is most efficient for finding the shortest path from a source to all other nodes in an unweighted graph?" options=["Dijkstra's Algorithm","Depth-First Search (DFS)","Breadth-First Search (BFS)","Bellman-Ford Algorithm"] answer="Breadth-First Search (BFS)" hint="Consider the property of BFS exploring layer by layer." solution="BFS guarantees finding the shortest path in terms of number of edges for unweighted graphs because it explores all nodes at distance kk before exploring any node at distance k+1k+1. Its time complexity is O(V+E)O(V+E)."
    :::

    :::question type="MCQ" question="Dijkstra's algorithm is guaranteed to find the shortest path from a single source to all other vertices under which condition?" options=["The graph contains no cycles.","All edge weights are non-negative.","The graph is a Directed Acyclic Graph (DAG).","The graph is dense, i.e., EV2E \approx V^2."] answer="All edge weights are non-negative." hint="What kind of edge weights cause issues for Dijkstra's greedy approach?" solution="Dijkstra's algorithm relies on a greedy approach that assumes once a node's shortest distance is finalized, it will not be improved by paths through other nodes. This assumption holds true only if all edge weights are non-negative. If negative weights are present, Bellman-Ford or SPFA is required."
    :::

    :::question type="NAT" question="Consider a directed graph with vertices A, B, C, D and edges with weights: A 2\xrightarrow{2} B, A 7\xrightarrow{7} C, B 3\xrightarrow{3} C, B 5\xrightarrow{5} D, C 1\xrightarrow{1} D. Using Dijkstra's algorithm, what is the shortest distance from vertex A to vertex D?" answer="6" hint="Systematically apply relaxation and priority queue updates, tracking the minimum distances." solution="

  • Initialize distances: dist[A]=0\operatorname{dist}[A]=0, dist[B]=\operatorname{dist}[B]=\infty, dist[C]=\operatorname{dist}[C]=\infty, dist[D]=\operatorname{dist}[D]=\infty. Priority Queue PQ={(0,A)}\operatorname{PQ} = \{(0, A)\}.

  • Extract A (0).

  • * Relax A 2\xrightarrow{2} B: dist[B]=min(,0+2)=2\operatorname{dist}[B] = \min(\infty, 0+2) = 2. PQ={(2,B)}\operatorname{PQ} = \{(2, B)\}.
    * Relax A 7\xrightarrow{7} C: dist[C]=min(,0+7)=7\operatorname{dist}[C] = \min(\infty, 0+7) = 7. PQ={(2,B),(7,C)}\operatorname{PQ} = \{(2, B), (7, C)\}.
  • Extract B (2).

  • * Relax B 3\xrightarrow{3} C: dist[C]=min(7,2+3)=5\operatorname{dist}[C] = \min(7, 2+3) = 5. Update C in PQ: PQ={(5,C),(7,C)}\operatorname{PQ} = \{(5, C), (7, C)\}.
    * Relax B 5\xrightarrow{5} D: dist[D]=min(,2+5)=7\operatorname{dist}[D] = \min(\infty, 2+5) = 7. PQ={(5,C),(7,C),(7,D)}\operatorname{PQ} = \{(5, C), (7, C), (7, D)\}.
  • Extract C (5).

  • * Relax C 1\xrightarrow{1} D: dist[D]=min(7,5+1)=6\operatorname{dist}[D] = \min(7, 5+1) = 6. Update D in PQ: PQ={(6,D),(7,D)}\operatorname{PQ} = \{(6, D), (7, D)\}.
  • Extract D (6). No outgoing edges to relax.

  • The shortest distance from A to D is 6.
    "
    :::

    ---

    What's Next?

    💡 Continue Your CMI Journey

    Having mastered shortest paths in graphs with non-negative weights, your journey in graph theory should now progress to understanding algorithms that handle more complex scenarios. Explore the Bellman-Ford algorithm for single-source shortest paths in graphs with negative edge weights, and then delve into Floyd-Warshall or Johnson's algorithm for computing all-pairs shortest paths. Additionally, consider adjacent problems such as finding Minimum Spanning Trees (Prim's and Kruskal's algorithms), which share conceptual similarities in their greedy approaches and priority queue usage.

    🎯 Key Points to Remember

    • Master the core concepts in Shortest Path Algorithms before moving to advanced topics
    • Practice with previous year questions to understand exam patterns
    • Review short notes regularly for quick revision before exams

    Related Topics in Graph Theory

    More Resources

    Why Choose MastersUp?

    🎯

    AI-Powered Plans

    Personalized study schedules based on your exam date and learning pace

    📚

    15,000+ Questions

    Verified questions with detailed solutions from past papers

    📊

    Smart Analytics

    Track your progress with subject-wise performance insights

    🔖

    Bookmark & Revise

    Save important questions for quick revision before exams

    Start Your Free Preparation →

    No credit card required • Free forever for basic features