Week 14: Shortest Path

Computer Algorithms (506994-002)

Ridho Hendra, Ph.D · Dept. of Intelligent Computing · Mon [1-3] · Building A, Room 703
Department of Intelligent Computing

Where We Are

Wk 1
Introduction
Wk 2
Algorithm Concepts
Wk 3
Complexity Analysis
Wk 4
Recursion & Recurrence
Wk 5
Basic Sorting
Wk 6
Advanced Sorting
Wk 7
Searching
Wk 8
Midterm Exam
Wk 9
Divide & Conquer
Wk 10
Greedy Algorithms
Wk 11
Dynamic Programming I
Wk 12
Dynamic Programming II
Wk 13
Graph Representation
Wk 14
Shortest Path
Wk 15
Final Exam
Department of Intelligent Computing

Last Week, This Week

  • Last week delivered: CampusNav finally represents the whole
    campus
    as a graph - buildings and junctions as nodes, walkways as
    weighted edges - and picked adjacency list over matrix once the
    real campus's sparse walkway network was shown numerically.
  • Last week left broken: having a graph lets CampusNav draw the
    campus and visit every node, but it still can't answer the one
    question every visitor actually asks: what's the cheapest way to
    get from A to B?
Department of Intelligent Computing

The Map Exists. The Directions Don't.

CampusNav now shows a beautiful map of the whole campus - every
building, every walkway, every junction, all connected correctly.
A first-year student opens it and taps "Get Directions: Gate to
CS Building." Nothing happens. There is no button that actually
computes a route. The student can see six or seven different paths
on the screen, all technically valid, and still has to guess which
one is fastest - by eye, the same way they'd guess at a printed
map. The graph CampusNav built last week can be looked at. It cannot
yet be asked a question.

Department of Intelligent Computing

What Else This Actually Costs

  • Guessing "by eye" which of several routes is shortest works on a
    6-node toy graph - it silently breaks the moment the graph has
    hundreds of junctions and the shortest route isn't the visually
    obvious one.
  • A wrong "shortest route" isn't just inconvenient - it's the kind of
    bug a user notices immediately and stops trusting the app for.
  • Every GPS app, ride-hailing app, and network router on Earth
    answers exactly this question, millions of times a second.
In industry: Dijkstra's algorithm is one of the most asked algorithms in technical interviews, and its real-world twin - network routers finding the cheapest path for a packet - runs this exact computation continuously, at massive scale, every day.
Department of Intelligent Computing

This Week's Question

"Given a weighted map and a starting point, how do we compute the cheapest route to every other place - provably, not by guessing - and what happens when a 'shortcut' can be worth a negative cost?"
Department of Intelligent Computing

By the End of This Week, You Can

  1. Trace Dijkstra's algorithm by hand on a small weighted graph, updating tentative distances round by round.
  2. Explain why Dijkstra's greedy strategy fails in the presence of negative edge weights, with a concrete counterexample.
  3. Trace Bellman-Ford's algorithm, explain why V−1 relaxation rounds suffice, and use one extra pass to detect a negative cycle.
  4. State the difference between P and NP precisely, and classify shortest path and the campus scavenger hunt correctly.
Department of Intelligent Computing

Key Words Today

  • Shortest path: the minimum-total-weight way to get from one vertex to another along the graph's edges.
  • Source vertex: the fixed starting point a single-source shortest-path algorithm computes distances from.
  • Weighted graph: a graph where every edge carries a cost (here: walking minutes), not just a yes/no connection.
  • Tentative distance: the best known so far cost to reach a vertex - may still improve as the algorithm runs.
Department of Intelligent Computing

Where This Idea Came From

Two names, two decades, two different pains - both still running inside your GPS today.
  • 1959, Edsger Dijkstra: by his own account, he designed the
    algorithm in about 20 minutes at a café table in Amsterdam, without
    pencil or paper, while thinking about the shortest route between
    two Dutch cities - then spent the next few days working out why it
    was correct. It was first published as a solution to exactly this
    kind of routing problem.
  • 1958, Richard Bellman (and, independently, Lester Ford
    slightly earlier, in routing/network-flow work): developed a
    slower but more general method - one that keeps working even when
    some edges are allowed to have negative weight, something
    Dijkstra's method cannot handle.
Department of Intelligent Computing

One Problem, Two Names

Same underlying question, solved twice, one year apart.
Both were solving the same underlying problem that shows up in road networks, telephone routing, and - decades later - the internet itself: given costs on connections, find the cheapest path through the network.
Department of Intelligent Computing

Single-Source Shortest Path: Definition

Formal, now that the pain is fresh. (CLRS - Cormen/Leiserson/Rivest/Stein's Introduction to Algorithms, 4th ed, Ch 22)

Given a weighted graph with edge weights and
a single source vertex , the single-source shortest path
problem
asks: for every vertex , find the minimum total
weight of any path from to - its shortest-path
distance
, written .

Department of Intelligent Computing

The Graph We're Working With

CampusNav's small six-location graph, reused from last week - Gate is today's source:
3 2 4 5 2 6 3 G L C D Y F
G Gate (source) · L Library · C CS-Building · D Dorm · Y Gym · F Cafeteria. Weights are walking minutes.
Department of Intelligent Computing

Key Words Today

  • Relaxation: checking whether going through a vertex gives a shorter known path to a neighbor than what's currently recorded, and updating it if so.
  • Greedy choice: at each step, commit to the locally best-looking option (smallest tentative distance) without reconsidering it later.
  • Priority queue: a data structure that always hands back the not-yet-finalized vertex with the smallest tentative distance, in .
  • Settled / finalized vertex: a vertex whose shortest-path distance is proven final - Dijkstra never revisits it.
Department of Intelligent Computing

Dijkstra's Algorithm: Idea and Pseudocode

Picture two routes to the Library: one "through the Dorm and the Gym," one "past the CS Building" - how do you know which is shorter without walking both? (CLRS 4th ed, §22.3)
  1. Start at the source; its distance is 0, every other vertex starts at .
  2. Repeatedly pick the unvisited vertex with the smallest tentative distance - this one is now guaranteed final ("settled").
  3. Relax every edge out of it: if going through it makes a neighbor's distance shorter, update that neighbor.
  4. Repeat until every vertex is settled.

EXTRACT-MIN is the "settle the closest unvisited vertex" step; the
inner loop is relaxation.

DIJKSTRA(G, w, source):
    for each vertex v in G.V:
        dist[v] = infinity
        prev[v] = NIL
    dist[source] = 0
    Q = all vertices in G.V, keyed by dist[]
    while Q is not empty:
        u = EXTRACT-MIN(Q)
        for each vertex v adjacent to u:
            if dist[u] + w(u, v) < dist[v]:
                dist[v] = dist[u] + w(u, v)
                prev[v] = u
                DECREASE-KEY(Q, v, dist[v])
    return dist, prev
Why is step 2 safe? Because every remaining edge weight is non-negative, no unvisited vertex can later become cheaper than the one currently smallest - nothing can subtract from a distance. That single assumption is the whole algorithm's foundation, and exactly what breaks later this week.
Department of Intelligent Computing
Dijkstra · worked example 1 of 3 (simple)

Three Nodes: S, A, B

The smallest graph where the direct edge is not the shortest route.
GoalFind every shortest distance from S on S-A=2, S-B=5, A-B=1.
1
Settle S
dist[S]=0. Relax S's edges: A becomes 0+2=2, B becomes 0+5=5.
→
2
Settle A
Smallest unvisited: A (2). Relax A-B: 2+1=3 < 5, so B improves to 3.
→
3
Settle B
Only B left, now at 3. Final distances: S=0, A=2, B=3, via S→A→B - cheaper than the direct S-B edge (5).
✓
Conclusionδ(S,A)=2, δ(S,B)=3 - the direct edge (5) is never the answer once a cheaper detour exists.
💡
Key takeawayRelaxation is what finds the detour - without it, Dijkstra would just report the direct edge's weight.
Department of Intelligent Computing
Dijkstra · worked example 2 of 3 (moderate)

The Campus Graph, Round by Round

Same six-location graph as this week's core example, source = Gate.
GoalSettle all six vertices and read off the shortest-path tree.
1
Rounds 1-2
Settle Gate(0): relax to Library=3, Dorm=4. Settle Library(3): relax to CS-Building=3+2=5, Gym=3+5=8.
→
2
Rounds 3-4
Settle Dorm(4): relax Dorm→Gym offers 4+6=10, not better than 8 - no change. Settle CS-Building(5): relax to Cafeteria=5+2=7.
→
3
Rounds 5-6
Settle Cafeteria(7), smaller than Gym's 8: relax Cafeteria→Gym offers 7+3=10 - no change. Settle Gym(8) last, nothing left to relax.
→
4
Reading the tree
Final, proven-optimal distances: Gate 0, Library 3, Dorm 4, CS-Building 5, Cafeteria 7, Gym 8. Tree: Gate→Library(3), Gate→Dorm(4), Library→CS-Building(5), CS-Building→Cafeteria(7), Library→Gym(8).
✓
ConclusionSix settles, six final distances - every vertex settled exactly once, in increasing distance order.
💡
Key takeawayCafeteria (7) settles before Gym (8) even though Gym was discovered first - Dijkstra always settles by tentative distance, never by discovery order.
Department of Intelligent Computing
Dijkstra · worked example 3 of 3 (harder)

Where Dijkstra Breaks: One Negative Edge

A clean, minimal counterexample - no lucky ties, just a wrong answer.
GoalShow Dijkstra reports the wrong distance the moment one edge is negative.
1
Setup
Source S. Directed edges: S→C=2, S→B=3, B→C=−4.
→
2
Settle S, then C
Settle S(0). Frontier: C=2, B=3. Smallest is C (2) - settle it, final. Dijkstra reports δ(S,C) = 2.
→
3
Settle B, relax B→C
Settle B(3). Relax B→C: candidate 3+(−4) = −1.
★
The wrong answer
−1 is less than C's distance of 2 - but C is already settled, so standard Dijkstra silently skips this update. True shortest distance, via S→B→C, is −1. Dijkstra's reported answer, 2, is simply wrong.
✓
ConclusionOne negative edge, no lucky tie: Dijkstra's "settle and never revisit" strategy reports 2 when the true answer is −1.
💡
Key takeawayDijkstra's correctness proof depends entirely on non-negative weights - with even one negative edge, no amount of "it happened to work here" is a guarantee.
Department of Intelligent Computing

Dijkstra's Complexity

Why bother with a priority queue at all? (Priority queue and binary heap: as introduced last week, Week 13.)
  • Each of the vertices is extracted from the priority queue
    exactly once: .
  • Each of the edges is relaxed at most once (when its tail
    vertex is settled), and each relaxation that improves a distance
    costs a DECREASE-KEY: .
O((V + E) log V)

with a binary-heap priority queue - the same insert/
extract-min fact Week 13 handed you as a tool. On CampusNav's real
campus graph (sparse - a junction connects to only a handful of
walkways, not every other junction), this is dramatically faster than
checking every possible route by hand, which grows exponentially with
the number of stops.

Department of Intelligent Computing

Key Words Today

  • Negative cycle: a cycle whose edge weights sum to less than zero - walking it repeatedly makes "shortest path" undefined, since you could loop forever and keep saving time.
  • Polynomial time: an algorithm's cost is bounded by for some fixed constant - this course's working definition of "efficient."
  • Verifiable: given a candidate answer, checking that it's correct can be done quickly - a different question from finding the answer.
  • NP-hard / NP-complete: at least as hard as every problem in NP; no known polynomial algorithm solves these, and none may exist.
Department of Intelligent Computing

The Covered Walkway

CampusNav's gamification team pitches a rainy-day feature.

To reward students for using a covered, roofed path between the
Cafeteria and the Library on rainy days, CampusNav's designers add a
"shortcut credit": walking that one specific direction, Cafeteria →
Library, is logged as −4 minutes instead of a normal positive
cost - a one-way perk, not a real physical shortcut.

3 2 4 5 2 6 3 -4 G L C D Y F
Department of Intelligent Computing

Dijkstra's Blind Spot

Re-run Dijkstra from Gate with the walkway edge added.
  • Dijkstra settles Library in round 2, at distance 3 - long
    before it ever reaches Cafeteria, which isn't settled until
    round 5, at distance 7.
  • Once Library is settled, the algorithm - by its own design - never
    looks at it again, even when it later discovers the −4 edge
    arriving at Library from Cafeteria.
  • If it did check: 7 + (−4) = 3. Here that happens to tie Library's
    existing answer - but Dijkstra never performs this check at all,
    and has no way of knowing in advance that it would only tie.
Department of Intelligent Computing

One Minute Worse, and There's No Answer At All

The tie above was luck. Push the credit one minute further.
Shave the shortcut credit by one more minute (−5 instead of −4) and the loop Library→CS-Building→Cafeteria→Library costs 2+2+(−5) = −1 minute per lap: a negative cycle. "Shortest path to Library" stops being a well-defined number - you could loop forever and save time forever. Dijkstra has no mechanism to notice this at all; it would simply report a wrong, finite answer.
Department of Intelligent Computing

Bellman-Ford: Idea and Pseudocode

If you can't trust "settle and never revisit," stop settling permanently. (CLRS 4th ed, §22.1)
  • Initialize distances exactly like Dijkstra: source = 0, everything
    else = .
  • Instead of picking one vertex at a time, relax every edge in the
    graph
    , in any order, once.
  • Repeat that full pass V − 1 times total.
  • No priority queue, no "settled" vertices - every distance stays
    open to improvement until the algorithm finishes, so a negative
    edge discovered late can still correct an earlier estimate.
BELLMAN-FORD(G, w, source):
    for each vertex v in G.V:
        dist[v] = infinity
        prev[v] = NIL
    dist[source] = 0
    for i = 1 to |G.V| - 1:
        for each edge (u, v) in G.E:
            if dist[u] + w(u, v) < dist[v]:
                dist[v] = dist[u] + w(u, v)
                prev[v] = u
    for each edge (u, v) in G.E:
        if dist[u] + w(u, v) < dist[v]:
            report "negative-weight cycle detected"
    return dist, prev
Department of Intelligent Computing
Bellman-Ford · worked example 1 of 3 (simple)

Three Nodes, One Negative Edge

The smallest graph where a negative edge actually changes the answer.
GoalFind every shortest distance from S on S→A=4, A→B=−2, S→B=5.
1
Setup
V=3, so V−1=2 rounds are required. dist[S]=0, dist[A]=dist[B]=∞.
→
2
Round 1
S→A: 0+4=4 < ∞, update A=4. A→B: 4+(−2)=2 < ∞, update B=2. S→B: 0+5=5, not < 2, no change.
→
3
Round 2
Every edge re-checked, nothing improves. Final: A=4, B=2, via S→A→B - beats the direct S→B edge (5).
✓
Conclusionδ(S,B)=2, not the direct edge's 5 - the negative edge made the detour through A the true shortest route.
💡
Key takeawayRound 2 found nothing new here, but Bellman-Ford has no way to know that in advance - it always budgets V−1 rounds.
Department of Intelligent Computing

Bellman-Ford on the Campus Graph

Same graph, same walkway edge, the algorithm that's actually safe to use.

Relaxing every edge (both directions of each walkway, plus the
one-way −4 walkway) just once, in the natural reading order,
already reaches the final answer:

 
Round 0
Round 1
Gate
0
0
Library
∞
3
Dorm
∞
4
CS-Bldg
∞
5
Gym
∞
8
Cafeteria
∞
7
Department of Intelligent Computing
Bellman-Ford · worked example 2 of 3 (moderate)

Round 1, Every Edge

The table above is the summary. Here is every single check that produced it, visiting G, L, C, D, Y, F in turn.
GoalRelax all 15 directed checks (7 undirected edges, both ways, plus the one-way credit) once.
1
Gate, Library
G→L: 0+3=3<∞, L=3. G→D: 0+4=4<∞, D=4. L→G: 3+3=6, not<0. L→C: 3+2=5<∞, C=5. L→Y: 3+5=8<∞, Y=8.
→
2
CS-Bldg, Dorm, Gym
C→L: 5+2=7, not<3. C→F: 5+2=7<∞, F=7. D→G: 4+4=8, not<0. D→Y: 4+6=10, not<8. Y→L: 8+5=13, not<3.
→
3
Gym, Cafeteria
Y→D: 8+6=14, not<4. Y→F: 8+3=11, not<7. F→Y: 7+3=10, not<8. F→C: 7+2=9, not<5. F→L(−4): 7−4=3, ties (not <3) - the credit only ties Library, never beats it.
→
4
Why it still runs 5 rounds
Round 1 already reached the final answer here - but Bellman-Ford cannot know that in advance, so it must still run all V−1=5 rounds to guarantee it. Rounds 2-5 change nothing; the extra check pass also finds nothing - no negative cycle, distances confirmed final.
✓
Conclusion15 edge checks, 4 improve a distance, 1 (the −4 credit) only ties - matching the summary table exactly.
💡
Key takeawayA different edge-visiting order could take longer than one round to converge - that's exactly why Bellman-Ford always budgets the full V−1 rounds.
Department of Intelligent Computing

Why V − 1 Rounds Suffice

Not a magic number - a direct consequence of what a shortest path can look like.
  • Assuming no negative cycle, any shortest path is a simple path
    (no repeated vertex) - so it uses at most edges.
  • Claim (by induction on rounds): after round , dist[v] is
    correct for every vertex whose true shortest path uses or fewer
    edges.
  • Round 1 correctly finds every shortest path of 1 edge (direct
    neighbors of the source). Round 2 extends that to 2-edge paths, and
    so on.
  • After round , every vertex's shortest path - which uses at
    most edges - has been found, no matter what order the edges
    were relaxed in.
Department of Intelligent Computing

Detecting Negative Cycles

The one extra pass Dijkstra could never offer.
  • If distances are truly final after rounds, one more full pass
    over every edge should change nothing.
  • If the -th pass still finds an edge it can relax, that
    improvement can only come from a negative-weight cycle
    reachable from the source - a loop you could walk forever, each
    lap making the "distance" smaller without bound.
  • Bellman-Ford reports this explicitly instead of returning a
    silently wrong number. Dijkstra has no equivalent check - it would
    never even reach that part of the graph in a way that reveals the
    problem.
Department of Intelligent Computing
Bellman-Ford · worked example 3 of 3 (harder)

A Steeper Credit Would Create a Cycle

Isolate the Library-CS-Building-Cafeteria loop and make the credit -5 instead of -4, purely to see what a real negative cycle does.
GoalShow why Bellman-Ford can only ever report this case, never silently guess a wrong number.
1
Setup
Isolated 3-edge cycle: L→C=2, C→F=2, F→L=−5. For illustration only, start dist[L]=0.
→
2
Lap 1
L→C: 0+2=2, C=2. C→F: 2+2=4, F=4. F→L: 4+(−5)=−1 < 0, update L=−1.
→
3
Lap 2
L→C: −1+2=1<2, C=1. C→F: 1+2=3<4, F=3. F→L: 3+(−5)=−2<−1, update L=−2.
★
It never stops
Each lap subtracts exactly 1 from L's distance, forever. The extra V-th pass always finds one more improvement, so Bellman-Ford correctly reports "negative-weight cycle detected" instead of a wrong finite number - exactly what Dijkstra has no mechanism to notice at all.
✓
ConclusionA single -1-per-lap cycle makes "shortest path" undefined - Bellman-Ford's extra pass is what catches it.
💡
Key takeawayThe deck's actual -4 credit leaves this loop at exactly 0 (no cycle) - this shows what happens once it tips negative.
Department of Intelligent Computing

Dijkstra vs. Bellman-Ford

Dijkstra Bellman-Ford
Negative weights Unsafe - can silently return the wrong distance Safe - always correct if no negative cycle
Negative cycles No detection at all Detects them (one extra pass)
Strategy Greedy - settle closest vertex, never revisit Relax every edge, every round, nothing is final until the end
Time complexity with a priority queue
When to use Non-negative weights, need speed (e.g. real road networks) Weights may be negative, or you need cycle detection
Department of Intelligent Computing

So Which One Does CampusNav Actually Ship?

The table says "it depends." Here's what it depends on, for this app.
CampusNav's real walkway network never has negative weights - so Dijkstra is what should actually ship. Bellman-Ford earns its keep the moment any feature (like a shortcut credit) can make an edge negative.
Department of Intelligent Computing

P: Polynomial-Time Solvable

The class shortest path belongs to. (CLRS 4th ed, §34.1)

A problem is in P if there exists an algorithm that solves
it - produces a correct answer, for every valid input - in time
bounded by for some fixed constant , where is the
input size.

  • Sorting: - in P.
  • Binary search: - in P.
  • Single-source shortest path: or - in P.
  • "In P" means solvable efficiently and completely, not just
    quickly on one instance you happened to try.
Department of Intelligent Computing

NP: Polynomial-Time Verifiable

The most common misconception in this entire topic - let's fix it directly. (CLRS 4th ed, §34.2)

A problem is in NP if, given a candidate solution, you can
verify whether it's correct in polynomial time - even if
finding
that solution might take far longer.

Common misconception: "NP means not solvable in polynomial time." That is false. NP stands for Nondeterministic Polynomial time - it is entirely about how fast a solution can be checked, not about how slow it is to find. Every problem in P is also in NP (if you can solve it fast, you can certainly verify a solution fast - just solve it and compare). The open question is whether the reverse is also always true.
Department of Intelligent Computing

The Campus Scavenger Hunt: NP-Hard

Same campus graph, one extra constraint, a completely different kind of problem.

CampusNav's events team pitches a new feature: a single scavenger
hunt route that visits every building on campus exactly once,
minimizing total walking distance.

  • Verifying a proposed route is fast: check every building
    appears exactly once, sum the weights - polynomial time, so this
    problem is in NP.
  • Finding the optimal route is a different story: this is
    shaped exactly like the Hamiltonian-path / Traveling
    Salesman
    problem - no known algorithm solves it faster than
    roughly trying all orderings, which is exponential in the number
    of buildings. Knowing how to solve shortest path (one destination)
    gives no shortcut here - a fundamentally different shape of problem.
Department of Intelligent Computing
P vs. NP · worked example

Verifying a Scavenger-Hunt Route, By Hand

"Hard to find" and "hard to check" are not the same claim - watch the check actually happen. (CLRS 4th ed, §34.2)
GoalVerify a candidate route in polynomial time, without solving the harder search problem.
1
The candidate
Gate → Dorm → Gym → Cafeteria → CS-Building → Library. Check 1: all six locations appear exactly once - one pass, O(V).
→
2
Check every edge
Gate→Dorm(4), Dorm→Gym(6), Gym→Cafeteria(3), Cafeteria→CS-Building(2), CS-Building→Library(2) - all five pairs are real edges, one adjacency-list lookup each.
→
3
Sum it
4+6+3+2+2 = 17 minutes total. Verified valid, in five quick lookups plus one pass over the list.
★
Fast to check, slow to find
Verifying took O(V) work. Finding this route among all orderings of six locations (up to 6!/2 = 360 distinct routes) offers no comparable shortcut - that gap is exactly what puts the scavenger hunt in NP without putting it in P.
✓
ConclusionA candidate route verifies in a handful of lookups; no known method finds the best one nearly as fast.
💡
Key takeawayNP is about how fast a solution can be checked - not how slow it is to find, the most common mix-up here.
Department of Intelligent Computing

NP-Complete, NP-Hard, and P =? NP

The open question underneath all of this - and why it matters.
  • A problem is NP-complete if it's in NP and every other
    problem in NP can be transformed into it in polynomial time - the
    "hardest" problems within NP. The scavenger hunt is one of these.
  • NP-hard problems are at least as hard as NP-complete ones, even
    if they aren't themselves required to be in NP.
  • Nobody has ever found a polynomial algorithm for any NP-complete
    problem, and nobody has proven one is impossible - P =? NP is
    one of the most famous open problems in mathematics and computer
    science (a Clay Millennium Prize problem).
Why we care: recognizing a new problem as NP-hard tells you, immediately, not to waste time hunting for a fast exact algorithm - a judgment call that matters far beyond CampusNav, in routing, scheduling, and resource-allocation systems everywhere.
Department of Intelligent Computing

CampusNav: Get Directions, Live

Everything above, together, on the actual feature.

The "Get Directions" button now runs Dijkstra over last week's graph
every time a student taps it. From the Gate:

Destination Shortest distance Route
Library 3 min Gate → Library
Dorm 4 min Gate → Dorm
CS-Building 5 min Gate → Library → CS-Building
Cafeteria 7 min Gate → Library → CS-Building → Cafeteria
Gym 8 min Gate → Library → Gym
Department of Intelligent Computing

What About the Covered Walkway?

The feature from earlier this week - shipped, but not the way it was pitched.

The covered-walkway credit stays in the app as a rainy-day display
feature, but it never feeds into the live Dijkstra computation - the
team learned this week exactly why that would be dangerous.

Department of Intelligent Computing

Common Mistakes

  • "Dijkstra works correctly with negative edge weights." It
    doesn't - its greedy "settle once, never revisit" strategy assumes
    no future discovery can ever beat an already-settled distance,
    which only holds when every remaining weight is non-negative.
  • "NP means not solvable in polynomial time." It means a
    candidate solution can be verified in polynomial time - a
    completely different, much weaker claim about checking, not
    finding.
  • Confusing "hard to solve" with "hard to verify." The scavenger
    hunt is hard to solve but easy to verify - that gap is the
    entire reason NP is an interesting class at all.
  • Assuming both campus problems share one complexity class.
    Shortest path is in P; the scavenger hunt is NP-complete.
Department of Intelligent Computing

Final Exam Blueprint

Full worked practice set (Weeks 9-14): see next week's Week 15 final review.
Department of Intelligent Computing

What This Week's Toolkit Cannot Do

Shortest path is solvable efficiently because it's in P - Dijkstra and Bellman-Ford both compute it in polynomial time, provably correctly. But closely related problems, like the scavenger-hunt route, may have no efficient algorithm at all, known or possible. Being able to solve one well-behaved problem in a family says nothing about the rest of that family - and for an entire class of important, everyday-shaped problems (P vs. NP), we do not yet know - and may never know - whether an efficient algorithm even exists.
Department of Intelligent Computing

Next Week

Week 14 leaves which problems have any efficient algorithm at
all
an open question - P vs. NP is unsolved, not just unsolved by
us
. There is no Week 16 to answer it. Week 15 is the Final Exam,
covering everything from Weeks 9-14: divide-and-conquer, greedy
algorithms, dynamic programming (twice), graph representation, and
this week's shortest path and P/NP material - with a full worked
practice set waiting for you there.

Department of Intelligent Computing

Where This Week Lives in CLRS

Everything above, mapped to the textbook - and where to look if you want more.
This week's topic CLRS 4th ed
Bellman-Ford algorithm §22.1
Dijkstra's algorithm §22.3
Polynomial time (the definition of "efficient") §34.1
Polynomial-time verification (P vs. NP) §34.2
If you want to go deeper (not required this semester): CLRS Chapter 21 (Minimum Spanning Trees - connecting every vertex as cheaply as possible, a different optimization goal than shortest path) and Chapter 23 (All-Pairs Shortest Paths - every vertex's distance to every other, not just from one source) are the natural next structures built on top of this week's single-source algorithms.
Department of Intelligent Computing

Summary

  • Dijkstra: greedy, settle-and-never-revisit, -
    correct only with non-negative weights, as the walkway edge showed.
  • Bellman-Ford: relax every edge times, - correct
    even with negative weights, and its extra pass detects negative
    cycles outright.
  • P = solvable in polynomial time. NP = a candidate solution
    is verifiable in polynomial time - not "unsolvable fast," the
    most common misreading.
  • Shortest path is in P; the campus scavenger hunt is NP-hard - same
    campus, two very different kinds of problem.
  • New: Week 14 Check - a short graded exercise on Dijkstra,
    Bellman-Ford, and P vs. NP, released now, due before Week 15
    begins, separate from Assignment 4 (see
    materials/assignments/week14-check.html).
Department of Intelligent Computing

Summary, Continued

  • Reading: CLRS, Chapter 22 - §22.1 (Bellman-Ford), §22.3
    (Dijkstra); Chapter 34 - §34.1 (polynomial time), §34.2
    (polynomial-time verification).
  • Prepare: work through Week 15's full practice set (seven
    questions, Weeks 9-14) without looking at the answers first.
Department of Intelligent Computing

Thank You

Department of Intelligent Computing

SLOT 1: Title

notes: Open with: "Last week CampusNav learned to draw the whole campus as a graph. This week it finally learns to answer the one question everyone actually asks a map app: what's the fastest way from here to there?" This is also the last new-content week - Week 15 is the final exam, covering Weeks 9-14. Flag the new Week 14 Check, due before Week 15 begins.

SLOT 2: Where we are

notes: Point at Week 14, then at Week 15. Say: "This is the last new technique of the semester. Next week is entirely review."

SLOT 3: Recap + open wound

SLOT 4: The pain (Act 1 / MOTIVATE), zero jargon

notes: Do not say "Dijkstra" or "shortest path algorithm" yet. Let the class feel that "we drew the map" and "we can navigate it" are not the same achievement.

SLOT 5: Cost of not knowing

SLOT 6: Driving question

SLOT 7: Learning outcomes

NEW: Key Words Today, session 1 (moved after Act 1 / MOTIVATE per SPINE.md's no-definition-before-slot-8 rule)

notes: Read each term aloud. Say these four words are what today's whole first half is built from.

SLOT 8: Origin (Act 2 / GROUND)

SLOT 9: Core concept (Act 2 / GROUND)

NEW: Key Words Today, session 2

notes: Read each term aloud. Say: "Every one of these words appears in the trace you're about to watch, step by step."

Act 3 / BUILD: Dijkstra idea + pseudocode merged, folds in the old warm-up's payload as a teacher-delivered lead-in

NEW: dense worked example, Dijkstra, simple tier

NEW: dense worked example, Dijkstra, moderate tier

NEW: dense worked example, Dijkstra, harder tier (the negative-weight counterexample)

NEW: Key Words Today, session 3

notes: Read each term aloud. Say: "By the end of today these four words fully separate two kinds of problems: ones we can solve fast, and ones we currently can only check fast."

Bellman-Ford idea + pseudocode merged

NEW: dense worked example, Bellman-Ford, simple tier

NEW: dense worked example, Bellman-Ford, moderate tier (absorbs the 3 edge-by-edge slides and the "still runs 5 more rounds" slide)

NEW: dense worked example, Bellman-Ford, harder tier (negative-cycle detection)

NEW: dense worked example, verifying a scavenger-hunt route (merges 3 slides into one graduated example)

SLOT N-2: Worked example

SLOT N-1: Common mistakes

Pointer slide, points to Week 15's full worked practice set

SLOT N+1: Limits (Act 4 / CLOSE)

SLOT N+2: Bridge (Act 4 / CLOSE)

NEW: CLRS reference slide, positioned immediately before Summary per course design

SLOT N+3: Summary (Act 4 / CLOSE)

SLOT N+4: Thank You