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 and in a graph is a path containing the minimum number of edges. The length of this path, denoted , is the shortest distance between and .
The shortest path length between vertices and is the minimum number of edges in any path connecting and . If no path exists, .
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 where and . We find the shortest path length from to .
Step 1: Identify paths from to .
> Path 1: , length 3.
> Path 2: , length 3.
> Path 3: , length 3.
Step 2: Determine the minimum length.
The minimum length among all paths is 3.
Answer: .
:::question type="MCQ" question="Given a graph with vertices and edges . 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:
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 . It inherently finds shortest paths in unweighted graphs because it discovers all vertices at distance from before discovering any vertices at distance .
:::algorithm title="BFS for Shortest Paths"
a. Dequeue a vertex .
b. For each neighbor of :
i. If (i.e., is unvisited):
Set .
Enqueue .
:::
Worked Example: BFS Trace for Shortest Distances
Consider the graph from the previous example: and . We use BFS to find shortest path lengths from to all other vertices.
Step 1: Initialization.
> , , , , , .
>
Step 2: Dequeue . Neighbors of are .
> . Enqueue .
> . Enqueue .
>
Step 3: Dequeue . Neighbors of are . is visited.
> . Enqueue .
>
Step 4: Dequeue . Neighbors of are . is visited. is visited ().
> . Enqueue .
>
Step 5: Dequeue . Neighbors of are . are visited.
> . Enqueue .
>
Step 6: Dequeue . Neighbors of are . are visited.
>
Step 7: Dequeue . Neighbors of are . are visited.
>
Answer: Shortest distances from : .
:::question type="NAT" question="In a graph with vertices and edges , 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.
> ,
Step 2: Dequeue 1. Neighbors: 2, 3.
> ,
> ,
Step 3: Dequeue 2. Neighbor: 4 (1 visited).
> ,
Step 4: Dequeue 3. Neighbor: 4 (1 visited, 4 visited with ).
>
Step 5: Dequeue 4. Neighbor: 5 (2, 3 visited).
> ,
Step 6: Dequeue 5. No unvisited neighbors.
>
The shortest path length from 1 to 5 is 3.
"
:::
---
3. Properties of Shortest Path Distances
For any two adjacent vertices in an unweighted graph, their shortest path distances from a source must be closely related.
For any edge and a source vertex , the shortest path distances satisfy:
Where: is the shortest distance from to , and is the shortest distance from to .
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 , either , , or . It cannot be that or , because if , we could form a shorter path to via of length .
Worked Example: Applying Shortest Path Edge Property
Consider a graph where . We examine possible values for if is an edge.
Step 1: Apply the formula.
>
>
Step 2: Solve for .
>
>
>
>
Answer: If and is an edge, then must be 4, 5, or 6.
:::question type="MSQ" question="Let be an unweighted graph and be a source vertex. For an edge , which of the following statements about and are always true?" options=[""," implies are in the same BFS layer","",""] answer="Option 1,Option 3,Option 4" hint="Recall the definition of shortest path distance and how it relates to adjacent vertices. If , then can be or ." solution="
"
:::
---
Advanced Applications
1. Degree Sum on Shortest Paths
Consider a shortest path between and . Vertices not on have specific constraints on how many neighbors they can have on . This property is critical for proving bounds on the sum of degrees of vertices on a shortest path.
Let be a shortest path from to . For any vertex , can be adjacent to at most two vertices on such that . More generally, can be adjacent to at most three vertices of to avoid creating a shorter path. If is adjacent to where , then at least two pairs or must have a path distance along . For example, if , then replacing with would shorten the path.
This property is a stronger form of the argument from the CMI PYQ. The PYQ statement says "if were adjacent to four vertices of , then two of them would be at distance at least along , and replacing that subpath by a two-edge route through would give a shorter path". This implies can be adjacent to at most 3 vertices of .
Worked Example: Illustrating the Adjacency Constraint
Let be a shortest path. Consider a vertex .
Step 1: Assume is adjacent to and .
> If is adjacent to and , we can form a path .
> The length of is 2.
> The length of (subpath of ) is 3.
> Since , replacing with would create a shorter path from to , contradicting being a shortest path.
Step 2: Conclude the constraint.
A vertex cannot be adjacent to and if . This means can connect to and only if .
Answer: If , it can be adjacent to (distance 1 along ), (distance 2 along ), or a single . It cannot connect to or further apart. This implies can be adjacent to at most 3 vertices on (e.g., ). If it connects to 4 vertices, say , then at least two must be separated by distance on , creating a shortcut.
:::question type="MCQ" question="Let be a shortest path in an unweighted graph . Consider a vertex . If is adjacent to and where , which of the following conditions must be true for to remain a shortest path?" options=["","","",""] answer="" hint="If , then the path segment has length . Could you create a shorter path using ?" solution="
If , then the subpath has length . If is adjacent to both and , we could replace the subpath with , which has length 2.
For to be a shortest path, this replacement must not create a shorter path. Thus, the length of must be less than or equal to 2.
So, .
If , , not two distinct vertices.
If , are adjacent on . Path length 1. . Valid.
If , . Path length 2. . Valid.
If , . Path length 3. If connects and , then has length 2, which is shorter than 3. This contradicts being a shortest path.
Therefore, .
"
:::
---
Problem-Solving Strategies
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.
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
❌ 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.
❌ 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 with 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 , 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 be a connected unweighted graph. If is the shortest path length from a source to vertex , and is a neighbor of , which of the following is NOT a possible value for ?" options=["","","",""] answer="" hint="Recall the shortest path edge property ." solution="The shortest path edge property states that for any edge , . This implies that can be , , or . It cannot be , because if it were, we could form a path from to of length by taking the shortest path to and then traversing the edge , which is shorter than , contradicting the definition of as the shortest path length."
:::
:::question type="MSQ" question="Let be a shortest path from to in an unweighted graph . Which of the following statements are necessarily true?" options=["Every subpath of is also a shortest path from to .","If is adjacent to and (), then .","The sum of degrees is always less than or equal to .","If is a tree, then is the unique path between and ."] answer="Every subpath of is also a shortest path from to x \notin V(P) v_i v_j i
"
:::
:::question type="NAT" question="Consider an grid graph. What is the shortest path length from the top-left vertex to the bottom-right vertex ?" 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 to in an grid graph, we need to make moves downwards and moves to the right. Each move corresponds to one edge. The total number of moves (edges) in any shortest path is ."
:::
:::question type="MCQ" question="Let be a connected graph with vertices. Let be a shortest path from to . The maximum length of can be at most:" options=["","","",""] answer="" hint="A simple path in a graph with 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 vertices, a simple path can have at most vertices. If a path has vertices, it has edges. This forms a Hamiltonian path. Since a shortest path cannot revisit vertices, its length is bounded by . For example, a path graph has vertices and a shortest path between its endpoints has length ."
:::
---
Summary
|
| Formula/Concept | Expression |
|---|----------------|------------| | 1 | Shortest Path Length | | | 2 | BFS for Unweighted SP | Layered exploration from source | | 3 | Shortest Path Edge Property | | | 4 | Subpath Optimality | Subpaths of SP are also SPs | | 5 | Vertex Adjacency to SP | adjacent to |---
What's Next?
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.
---
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.
Let be a path from to . The weight of the path is given by:
Where: is the weight of the edge connecting and .
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 and edges with weight , with weight , with weight , and with weight . We want to find the weight of the path .
Step 1: Identify the edges in the path.
> The path consists of edges and .
Step 2: Sum the weights of the edges.
>
>
>
Answer: The weight of the path is .
:::question type="MCQ" question="Given a graph with edges , where denotes an edge from to with weight . What is the weight of the path ?" 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 .
> The edges are , , and .
Step 2: Sum the weights of these edges.
>
>
>
The weight of the path is ."
:::
---
2. Algorithm Overview
Dijkstra's algorithm is a greedy algorithm that iteratively finds the shortest paths from a source vertex 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.
- 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 and edges , , , , . We want to find the shortest path from source to all other vertices. We will illustrate the first few steps of the greedy selection.
Step 1: Initialize distances and set as the source.
> , , , .
> Priority Queue .
Step 2: Extract minimum from .
> We extract . is now visited.
Step 3: Relax neighbors of .
> For neighbor : . Add to .
> For neighbor : . Add to .
> .
Step 4: Extract minimum from .
> We extract . is now visited.
Step 5: Relax neighbors of .
> For neighbor : . Update to in .
> For neighbor : . Add to .
> .
Answer: After these steps, the current shortest distance estimates are . The next vertex to be processed would be .
:::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 by going through .
Initialization:
Main Loop:
a. Extract vertex with the minimum from .
b. If has already been visited (its shortest path finalized), continue.
c. Mark as visited.
d. For each neighbor of :
i. Perform `relax(u, v, w(u,v))`.
Given an edge with weight :
If , then update:
Insert or update in the priority queue.
Where: is the current shortest distance estimate from the source to , is the weight of the edge .
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 and edges , , , , . Source is . We trace the full algorithm.
Step 1: Initialization
>
>
>
Step 2: Process
> Extract from .
> Relax neighbors of :
> For : . Update , . Add to .
> For : . Update , . Add to .
>
Step 3: Process
> Extract from .
> Relax neighbors of :
> For : . Update , . Update to in .
> For : . Update , . Add to .
>
Step 4: Process
> Extract from .
> Relax neighbors of :
> For : . Update , . Update to in .
>
Step 5: Process
> Extract from .
> has no unvisited neighbors.
>
Answer: The final shortest distances from are: . The shortest paths can be reconstructed using : .
:::question type="NAT" question="Consider a directed graph with vertices and edges , , , , . Using Dijkstra's algorithm from source , what is the shortest distance to vertex ?" answer="7" hint="Trace Dijkstra's algorithm step-by-step, performing relaxation operations and using a priority queue." solution="Step 1: Initialization
>
>
>
Step 2: Process
> Extract .
> Relax neighbors of :
> For : . , . Add to .
> For : . , . Add to .
>
Step 3: Process
> Extract .
> Relax neighbors of :
> For : . , . Add to .
> (order might vary based on tie-breaking for equal priorities)
Step 4: Process
> Extract .
> Relax neighbors of :
> For : . , . Add to .
>
Step 5: Process
> Extract .
> Relax neighbors of :
> For : . is currently . Since , no update.
>
Step 6: Process
> Extract .
> has no neighbors.
>
Answer: The final shortest distance to is . Oh, wait, I made a mistake in the trace. Let's re-evaluate the edge .
Let's re-trace focusing on the priority queue and relaxation:
Step 1: Initialization
>
>
Step 2: Process
> Extract .
> Neighbors of : .
> . Push to .
> . Push to .
>
Step 3: Process
> Extract .
> Neighbors of : .
> . Push to .
>
Step 4: Process
> Extract .
> Neighbors of : .
> . Push to .
>
Step 5: Process
> Extract .
> Neighbors of : .
> . No change to .
>
Step 6: Process
> Extract .
> has no neighbors.
>
The shortest distance to is . 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 . Edges , , , , .
The vertex is mentioned in but not in the list of vertices . This implies is also a vertex.
The path has weight .
The path has weight .
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 is 7, it means some path is shorter.
gives .
gives .
To get 7, maybe an edge with weight 7, or a different intermediate path.
Let's change the question graph to allow for a distance of 7.
E.g., if existed with weight 5, then would be .
Or if existed with weight 1, then would be .
Let's use a simpler graph to ensure correctness.
Vertices . Edges , , , . Shortest path to ?
: .
: .
Answer should be 5.
Let's take a new example for the NAT question.
Vertices . Edges . From to .
Shortest distance to is 5.
This is a better graph. I need to update the question.
:::question type="NAT" question="Consider a directed graph with vertices and edges , , , . Using Dijkstra's algorithm from source , what is the shortest distance to vertex ?" answer="5" hint="Trace Dijkstra's algorithm step-by-step, performing relaxation operations and using a priority queue." solution="Step 1: Initialization
>
>
Step 2: Process
> Extract .
> Relax neighbors of :
> For : . . Push to .
> For : . . Push to .
>
Step 3: Process
> Extract .
> Relax neighbors of :
> For : . . Push to .
>
Step 4: Process
> Extract .
> Relax neighbors of :
> For : . . Update to in .
>
Step 5: Process
> Extract .
> has no neighbors.
>
The shortest distance to is ."
:::
---
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.
❌ 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 and edges , , , . Source is .
Step 1: Initialization
>
>
Step 2: Process
> Extract .
> Relax neighbors of :
> For : . Add to .
> For : . Add to .
>
Step 3: Process
> Extract .
> Relax neighbors of :
> For : . Update to in .
>
Step 4: Process
> Extract .
> Relax neighbors of :
> For : .
> Since , should be updated to . However, has already been extracted and marked as visited. Dijkstra's algorithm does not re-process visited vertices.
>
Answer: Dijkstra's algorithm reports and . The true shortest path to is with weight . The true shortest path to is with weight . The algorithm failed to find the true shortest path to because was finalized before a shorter path through 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.
For any three vertices in a graph, the shortest path distance from to is less than or equal to the sum of the shortest path distance from to and the weight of the edge .
This property is fundamental to the correctness of relaxation-based algorithms like Dijkstra's and Bellman-Ford.
Worked Example:
Let denote the shortest path distance from vertex to vertex . Suppose in a graph with positive edge weights, and . If there is an edge with weight , what can we infer about ?
Step 1: Apply the triangle inequality.
> We know that the shortest path from to cannot be longer than the path that goes from to and then directly to .
>
Step 2: Substitute the given values.
>
Step 3: Solve for .
>
>
Answer: The weight of the edge must be greater than or equal to .
:::question type="MSQ" question="Let be a directed graph with distinct and non-negative edge weights. Let be a starting vertex and a destination vertex. Assume that has at least one - path. Which of the following statements are always true?" options=["Every shortest - path must include the minimum-weight edge of .","Every shortest - path must exclude the maximum-weight edge of .","If and are shortest path distances from to and respectively, and is an edge with weight , then .","A shortest - path does not contain any cycles."] answer="If and are shortest path distances from to and respectively, and is an edge with weight , then ,A shortest - 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 - path must include the minimum-weight edge of .' (False)
- 'Every shortest - path must exclude the maximum-weight edge of .' (False)
- 'If and are shortest path distances from to and respectively, and is an edge with weight , then .' (True)
- 'A shortest - path does not contain any cycles.' (True)
:::
---
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 cities and one-way roads. Each road has a travel time (weight). We want to find the fastest route from a source city to a destination city , but we are allowed to take a single flight (which has a fixed cost ) from any city to any other city , provided there's no direct road from to . If there is a direct road, a flight is not allowed between and .
Step 1: Model the problem as a graph.
> We can create a 'layered' graph. Create two copies of the original graph, and .
> : Represents the state 'no flight taken yet'.
> : Represents the state 'one flight has been taken'.
> Vertices in are , vertices in are .
Step 2: Add edges to the layered graph.
> For every original road with weight , add edges in with weight , and in with weight .
> For every pair of cities where there is NO direct road in the original graph, add an edge from to with weight . This represents taking the flight.
Step 3: Run Dijkstra's algorithm.
> Run Dijkstra's algorithm from the source (in , i.e., ).
> The shortest path to would be the shortest path without any flight.
> The shortest path to would be the shortest path using exactly one flight.
> The overall fastest route is .
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 ) to a customer (destination ) in a city. The city map is a directed graph with intersections and 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 to any other intersection (even if there's a street between them). This warp takes minutes, regardless of distance. What is the minimum travel time from to if the drone can use the warp at most once? Assume , , . The graph edges are: . Calculate the shortest time from to 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: (no warp used) and (warp used).
> Vertices in : .
> Vertices in : .
Step 2: Add edges within layers.
> For each original edge :
> Add to .
> Add to .
> Edges:
> And similar for .
Step 3: Add warp edges between layers.
> For every pair of vertices in the original graph, add an edge (warp cost).
> Warp edges (cost 10):
>
>
> etc.
Step 4: Run Dijkstra's from .
> We are interested in and . The minimum of these will be the answer.
Trace Dijkstra's from :
> Initial , all others .
>
> Pop :
> . Push .
> . Push .
> Warp from :
> . Push .
> . Push .
> . Push .
> . Push .
>
> Pop :
> . Push .
> Warp from :
> . Push .
> . No change.
> . No change.
> . No change.
>
> Pop :
> . Push .
> Warp from :
> . No change.
> . No change.
> . No change.
> . No change.
>
> Pop :
> . No change.
> . No change.
> Warp from :
> . No change.
> . No change.
> . No change.
> . No change.
>
> Pop :
> Shortest path to is 7.
> At this point, we have found a path to with cost 7. We also have from (direct warp).
> The shortest path to is .
Answer: The minimum travel time from to is ."
:::
---
Problem-Solving Strategies
When tracing Dijkstra's algorithm, maintain a table of current shortest distances `dist[v]` and predecessors `prev[v]` for all vertices . 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.
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
❌ 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.
❌ 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 with weight as two directed edges and . Ensure all edge weights are positive.
❌ 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 and edges with positive weights: . If we run Dijkstra's algorithm starting from vertex , what is the shortest distance to vertex ?" options=["7","8","9","10"] answer="7" hint="Trace Dijkstra's algorithm, keeping track of distances and the priority queue. The path is one candidate." solution="Step 1: Initialization
>
>
Step 2: Process
> Extract .
> . Push to .
> . Push to .
>
Step 3: Process
> Extract .
> . Update to in .
> . Push to .
>
Step 4: Process
> Extract .
> . Push to .
>
Step 5: Process
> Extract .
> has no neighbors.
> The shortest distance to is .
Wait, there is an edge .
Let's retry the trace carefully.
Step 1: Initialization
>
>
Step 2: Process
> Extract .
> . Add to .
> . Add to .
>
Step 3: Process
> Extract .
> . Update to in .
> . Add to .
>
Step 4: Process
> Extract .
> . Add to .
>
Step 5: Process
> Extract .
> has no unvisited neighbors.
> The current shortest distance to is 6.
Let's check the path . Weight .
Let's check . Weight .
Let's check . Weight .
The shortest distance to 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 from 3 to 4.
Then would be .
And would be .
And would be .
So the shortest path to would be 7. This matches one of the options.
Revised Question:
Vertices and edges with positive weights: . If we run Dijkstra's algorithm starting from vertex , what is the shortest distance to vertex ?
Revised Solution:
Step 1: Initialization
>
>
Step 2: Process
> Extract .
> . Add to .
> . Add to .
>
Step 3: Process
> Extract .
> . Update to in .
> . Add to .
>
Step 4: Process
> Extract .
> . Add to .
>
Step 5: Process
> Extract .
> has no unvisited neighbors.
> The shortest distance to is .
Answer: The shortest distance to is ."
:::
:::question type="NAT" question="A directed acyclic graph (DAG) has vertices and edge weights: . What is the shortest distance from to 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
>
>
Step 2: Process
> Extract .
> . Push to .
> . Push to .
>
Step 3: Process
> Extract .
> . Push to .
> . Push to .
>
Step 4: Process (or , tie-breaking doesn't affect final answer)
> Extract .
> . No change.
>
Step 5: Process
> Extract .
> . Update to in .
>
Step 6: Process
> Extract .
> has no neighbors.
> The shortest distance to is .
Answer: The shortest distance from to is ."
:::
:::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 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 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)
- 'Its time complexity is using a binary heap priority queue.' (True)
- 'It can find shortest paths from a single source to all reachable vertices.' (True)
- 'It is a dynamic programming algorithm.' (False)
:::
:::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 is reduced. What is the most efficient way to update the shortest path from a source to a destination ?" options=["Rerun Dijkstra's algorithm from to on the modified graph.","Run Bellman-Ford algorithm from to .","The shortest path cannot be shorter, so no update is needed.","Only update the path if was the original shortest path, by reducing its total weight."] answer="Rerun Dijkstra's algorithm from to on the modified graph." hint="Consider the global impact of a local change on shortest paths." solution="Explanation:
- 'Rerun Dijkstra's algorithm from to on the modified graph.' (Correct)
- 'Run Bellman-Ford algorithm from to .' (Incorrect)
- 'The shortest path cannot be shorter, so no update is needed.' (Incorrect)
- 'Only update the path if was the original shortest path, by reducing its total weight.' (Incorrect)
:::
---
Summary
|
| Formula/Concept | Expression |
|---|----------------|------------| | 1 | Path Weight | | | 2 | Relaxation | If , then | | 3 | Triangle Inequality | | | 4 | Time Complexity (Binary Heap) | | | 5 | Requirement | Non-negative edge weights | | 6 | Purpose | Single-source shortest paths |---
What's Next?
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
Unweighted Shortest Path: Breadth-First Search (BFS) efficiently finds shortest paths in terms of edge count for unweighted graphs, with a time complexity of .
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 of a vertex is updated if a shorter path through is found: .
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 or for dense graphs where .
* 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 before exploring any node at distance . Its time complexity is ."
:::
:::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., ."] 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 B, A C, B C, B D, C 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="
* Relax A B: . .
* Relax A C: . .
* Relax B C: . Update C in PQ: .
* Relax B D: . .
* Relax C D: . Update D in PQ: .
The shortest distance from A to D is 6.
"
:::
---
What's Next?
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.