01 / 20

Shortest Path
Algorithms

Discover how BFS and Dijkstra's algorithm find the most efficient routes through graphs: the backbone of navigation, networking, and optimization.

Discrete Math

What is a Graph?

A graph \( G = (V, E) \) consists of a set of vertices (nodes) \( V \) and a set of edges \( E \) connecting them. Graphs model relationships: cities connected by roads, computers on a network, or friends in a social group.

A B C D E \( G = (V, E) \) with \( |V| = 5 \), \( |E| = 6 \)

Weighted vs Unweighted Graphs

Unweighted
Every edge has the same cost (implicitly \( 1 \)). Distance = number of edges traversed.
Weighted
Each edge carries a numeric weight \( w(u, v) \). Distance = sum of weights along a path.
Unweighted S A T B Weighted 2 3 1 4 10 S A T B

Why Shortest Paths Matter

Shortest path algorithms power critical systems you use every day. Understanding them opens the door to graph theory, optimization, and algorithm design.

Navigation
GPS systems find the fastest route between two locations on a road network.
Networking
Internet routers forward packets along the lowest-cost path to a destination.
Social Graphs
"Degrees of separation" between people is computed with BFS on the friendship graph.

BFS: Breadth-First Search

BFS explores a graph layer by layer. Starting from a source vertex \( s \), it visits all neighbors at distance \( 1 \), then distance \( 2 \), and so on. It uses a queue (first-in, first-out) to track the frontier.

Layer 0 Layer 1 Layer 2 S A B C D E \( d = 0 \) \( d = 1 \) \( d = 2 \)

BFS Step by Step

1
Initialize: set \( \text{dist}[s] = 0 \), all others to \( \infty \). Enqueue \( s \).
2
Dequeue the front vertex \( u \) from the queue.
3
Explore neighbors: for each unvisited neighbor \( v \) of \( u \), set \( \text{dist}[v] = \text{dist}[u] + 1 \), then enqueue \( v \).
4
Repeat steps 2-3 until the queue is empty.

Dijkstra's Algorithm: The Big Idea

Dijkstra's algorithm generalizes BFS to weighted graphs with non-negative edge weights. Instead of a simple queue, it uses a priority queue (min-heap) that always processes the vertex with the smallest tentative distance next.

Dijkstra's Step by Step

1
Initialize: set \( \text{dist}[s] = 0 \), all others to \( \infty \). Insert all vertices into a min-heap.
2
Extract the vertex \( u \) with the smallest \( \text{dist}[u] \) from the heap.
3
Relax edges: for each neighbor \( v \) of \( u \), if \( \text{dist}[u] + w(u,v) < \text{dist}[v] \), update \( \text{dist}[v] \).
4
Repeat steps 2-3 until the heap is empty or the target is finalized.

BFS vs Dijkstra

BFS Dijkstra
Graph type Unweighted Weighted (non-negative)
Data structure Queue (FIFO) Priority queue (min-heap)
Distance metric Edge count Sum of edge weights
Time complexity \( O(|V| + |E|) \) \( O((|V| + |E|) \log |V|) \)
Negative weights? N/A Not supported

The Relaxation Operation

Relaxation is the core operation in Dijkstra's algorithm. When we process vertex \( u \) and examine edge \( (u, v) \), we check whether going through \( u \) gives a shorter path to \( v \):

if \( \text{dist}[u] + w(u, v) < \text{dist}[v] \):
    \( \text{dist}[v] = \text{dist}[u] + w(u, v) \)
    \( \text{prev}[v] = u \)  // track the path
Before Relaxation u v dist = 3 dist = 10 w = 2 → After Relaxation u v dist = 3 dist = 5 w = 2

How to Apply These Algorithms

1
Model the problem as a graph: identify vertices, edges, and whether edges are weighted.
2
Choose the right algorithm: unweighted → BFS. Non-negative weights → Dijkstra.
3
Initialize distances: source \( = 0 \), all others \( = \infty \). Set up the data structure (queue or heap).
4
Process vertices: dequeue/extract-min, relax neighbors, update distances.
5
Reconstruct the path: use the prev[] array to trace back from target to source.

Example 1: BFS on an Unweighted Graph

S A B C D T d = 0 d = 1 d = 1 d = 2 d = 2 d = 3

Example 2: Dijkstra on a Weighted Graph

4 1 1 6 2 3 5 8 S A B C D T

Dijkstra Trace Table

Here is the step-by-step processing order for the graph from Example 2:

Step Extract dist[] Relaxed
1 S (0) A:4, B:1 A, B
2 B (1) D:3 D
3 D (3) T:11 T
4 A (4) C:5 C
5 C (5) T:10 T updated
6 T (10) Done —

Example 3: Choosing the Right Algorithm

A social network has 500 users. You want to find the fewest number of friend connections between User A and User B. Each friendship is a direct, equal-cost link.

✓ BFS
All friendships have equal weight (unweighted). BFS finds the fewest-hop path in \( O(|V| + |E|) \).
✕ Dijkstra
Overkill: the priority queue adds unnecessary \( \log |V| \) overhead when all weights are \( 1 \).

Common Mistakes

✕ Using BFS on Weighted Graphs
BFS counts edges, not weights. On a weighted graph, the fewest-edge path is often not the lowest-cost path.
✕ Dijkstra with Negative Weights
Dijkstra's greedy strategy fails with negative edges. A finalized vertex could later be improved, violating correctness.
✕ Forgetting to Track prev[]
Computing \( \text{dist}[] \) alone tells you the cost but not the actual path. Always maintain a predecessor array.

Summary at a Glance

BFS Dijkstra
Best for Unweighted shortest path Weighted shortest path (\( w \geq 0 \))
Core structure FIFO queue Min-heap / priority queue
Key operation Visit layer by layer Relax edges greedily
Time \( O(|V| + |E|) \) \( O((|V|+|E|)\log|V|) \)
Space \( O(|V|) \) \( O(|V|) \)
Negative weights N/A Not supported
Optimal for equal-weight ✓ Yes, preferred Works but slower

Question 1 of 5

In BFS, what data structure is used to manage the frontier of vertices to explore next?

Question 2 of 5

Dijkstra's algorithm requires that all edge weights are:

Question 3 of 5

You have a graph where every edge has weight \( 1 \). Which algorithm is the best choice for finding the shortest path?

Question 4 of 5

During Dijkstra's algorithm, vertex \( u \) has \( \text{dist}[u] = 7 \). Edge \( (u, v) \) has weight \( 3 \), and currently \( \text{dist}[v] = 12 \). After relaxing this edge, what is \( \text{dist}[v] \)?

Question 5 of 5

What is the time complexity of Dijkstra's algorithm when implemented with a binary min-heap?