Shortest Path Algorithms in Weighted Graphs

Learn how to find the lightest route through a network whose edges carry distances, times or costs. Relax edges in topological order to solve directed acyclic graphs in linear time, use Dijkstra's algorithm with a priority queue when weights are nonnegative, and use Bellman–Ford when weights can be negative, including detecting negative cycles. Compare methods for distances between all pairs of vertices, and model route planning on maps, project schedules and currency arbitrage as shortest-path problems.

IntermediateLesson 9 of 10 in Data Structures and Algorithms Course

What you will learn

  1. Represent networks whose edges carry costs, state exactly what a shortest path and a distance are in every case, and use relaxation, the step that all shortest-path algorithms in this material share.
    • Represent weighted graphs and see why BFS is not enough
      Store directed and undirected weighted graphs, decide what the weights measure, and explain why the path with the fewest edges is not always the lightest one.
    • Define distances, negative cycles and shortest-path trees
      State what the distance from a source is when a vertex is reachable, unreachable or reachable through a negative cycle, and record the paths themselves with parent pointers.
    • Relax edges to improve distance estimates
      Keep a distance estimate for every vertex, lower it with the relaxation step, and use the triangle inequality to tell when the estimates are exact.
  2. Compute single-source shortest paths in a directed acyclic graph in linear time by relaxing edges in topological order, even with negative weights, and adapt the method to longest paths and project schedules.
    • Run DAG relaxation in topological order
      Process the vertices of a DAG in topological order, relax each outgoing edge once, and explain why the result is correct in O(V+E) time.
    • Find longest paths and critical paths in a DAG
      Turn a longest-path question on a DAG into a shortest-path question and use it to find the minimum length and the critical jobs of a project with precedence constraints.
  3. Find single-source shortest paths in graphs with nonnegative weights by repeatedly finishing the closest vertex, implement this with a priority queue, analyze its running time, and recognize the inputs on which it fails.
    • Trace Dijkstra's algorithm step by step
      Run Dijkstra's algorithm by hand on a graph with nonnegative weights, explain why the vertex it finishes has its final distance, and connect it to BFS.
    • Implement Dijkstra's algorithm with a priority queue and analyze it
      Code Dijkstra's algorithm with a binary heap, handle outdated queue entries, and compare its running time with other priority-queue choices.
    • Explain why negative weights break Dijkstra's algorithm
      Use a small counterexample to show how a negative edge leads Dijkstra's algorithm to a wrong distance, and choose a correct algorithm instead.
  4. Compute single-source shortest paths in any weighted directed graph, including graphs with negative weights, and detect, locate and interpret negative cycles.
    • Run Bellman–Ford in rounds of relaxation
      Relax every edge in V−1 rounds, explain why that many rounds are enough, and trace and analyze the algorithm.
    • Detect, find and use negative cycles
      Use an extra round of relaxation to detect a negative cycle reachable from the source, recover the cycle, mark the affected vertices, and apply this to arbitrage.
  5. Compare the ways to find distances between every pair of vertices, choose the right shortest-path algorithm for a problem, and model route-planning questions on maps as weighted graphs.
    • Compute all-pairs shortest paths
      Compare repeated single-source runs, Floyd–Warshall and Johnson's algorithm for computing a full distance table, and trace Floyd–Warshall on a small graph.
    • Choose an algorithm and model routing and map problems
      Pick the right shortest-path algorithm from the graph and its weights, and turn route-planning questions on road maps into weighted graphs.

Shortest Path Algorithms study guide

5 chapters

1

Model weighted graphs and define shortest paths

A route can have fewer steps yet cost more. Weighted graphs make the objective explicit, whether the weights represent travel time, distance, or delay. Learn to store those costs, distinguish a finite distance from an unreachable or unbounded one, and recover an actual route with parent pointers. The relaxation step then gives a common way to improve a candidate distance before choosing a complete algorithm.

1.1 Store the costs that a route must minimize

A graph describes where a route can go. Its weights describe what the route costs. Before searching, choose whether a cost means distance, travel time, delay, or another quantity that adds along a route.

Keep direction and weight together

A weighted graph consists of vertices, edges, and a weight function. The value w(u,v) is the weight of the edge from u to v. A directed edge permits travel only in its arrow's direction. To represent an undirected edge of weight 5, store both u→v (5) and v→u (5).

An adjacency list stores each outgoing neighbor beside its weight:

graph = {
    "S": [("A", 4), ("B", 2)],
    "A": [("C", 5)],
    "B": [("A", 1), ("C", 8), ("D", 10)],
    "C": [("D", 2), ("T", 6)],
    "D": [("T", 2)],
    "T": []
}

Include vertices with no outgoing edges so that a loop over the dictionary sees the whole graph. A flat list of (u, v, w) triples is also useful when an algorithm scans every edge repeatedly.

Choose storage for the graph

An adjacency matrix stores the direct edge weight in row u, column v. Mark a missing edge with ∞ or another separate marker. Zero cannot mean "no edge": a free connection can genuinely weigh 0. Negative weights can model a gain, such as recovered energy or a refund. Their presence changes which shortest-path algorithms apply.

RepresentationSpaceUseful operation
Adjacency listO(V+E)Scan the edges leaving a vertex
Adjacency matrixO(V2)Look up a particular ordered pair

In these bounds, V and E mean the numbers of vertices and edges. Lists suit sparse graphs with relatively few edges. A matrix is useful for dense graphs, where many ordered pairs have an edge. Keeping only the neighbor names loses the costs needed by relaxation.

Compare total weight with hop count

BFS minimizes the number of edges. When every edge has the same positive weight, minimizing that count also minimizes cost. Unequal weights break that connection.

In the graph above, the routes with the fewest edges from S to T each have three edges. Their weights are:

  • S→B→D→T: 2+10+2=14.
  • S→A→C→T: 4+5+6=15.
  • S→B→C→T: 2+8+6=16.

The route S→B→A→C→D→T has five edges, yet weighs only 2+1+5+2+2=12. It is lighter than every three-edge route. "Shortest" in this setting means minimum total weight.

The weights must match one objective and one unit. Adding a segment measured in kilometers to a segment measured in minutes has no useful route interpretation. If the objective is travel time, store every segment's time; changing the objective to distance can change the winning route.

Key Takeaways

  • Each edge stores a direction and a weight; an undirected connection needs both directions.
  • Adjacency lists use O(V+E) space; matrices use O(V2).
  • Zero is a valid weight, so a matrix needs a separate missing-edge marker.
  • BFS minimizes hops; with unequal weights, a route with more edges can be lighter.

1.2 Distinguish a distance from the route that achieves it

A distance answers "How light can the route be?" A path answers "Which edges achieve that weight?" Some destinations have no route, and some have routes whose weights can decrease without limit.

Three possible distance values

The weight of a path is the sum of its edge weights. Its minimum possible weight is the distance, written δ(s,t).

SituationDistance from s to t
A minimum-weight route existsIts finite weight
No route reaches t∞
A route can reach a negative cycle and then reach t−∞

With no negative cycle, the source has distance 0 to itself: the empty path takes no edges. A negative cycle has a total weight below 0. For B→A (−2), A→C (3), and C→B (−5), one lap weighs −2+3−5=−4. Taking another lap lowers a route's weight by 4 again. No finite minimum exists for a destination reachable after that cycle.

The reachability conditions matter. A cycle in a separate component cannot affect a route from s. Even a cycle reachable from s affects t only if travel can continue from that cycle to t.

Why shorter pieces build a shortest path

Every segment of a shortest path is shortest between its own endpoints. Otherwise, replacing that segment with a lighter one would improve the whole route. This optimal substructure lets an algorithm build a route by extending already good routes.

When no negative cycle is reachable, a shortest route can be chosen to be simple, with no repeated vertex. A repeated vertex encloses a cycle of weight at least 0; removing that cycle cannot increase the weight. A simple path visits at most V vertices and uses at most V−1 edges. This edge bound will explain the number of Bellman–Ford rounds.

Rebuild a path from its parents

A parent pointer records the vertex immediately before a destination on its best known route. In the graph with edges S→A (4), S→B (2), B→A (1), A→C (5), B→C (8), B→D (10), C→D (2), C→T (6), and D→T (2), the final records are:

VertexDistanceParent
B2S
A3B
C8A
D10C
T12D

Starting at T, follow parents: T, D, C, A, B, S. Reverse that list to obtain S→B→A→C→D→T. The parent edges form a shortest-path tree rooted at S. A missing route remains unreachable; it has no source-rooted parent chain to reconstruct.

Different paths can tie for minimum weight. The distance stays the same, while the chosen parents can depend on tie-breaking.

Match the search to the query

Single-pair means one start and one target. Single-source means one start and every target. Single-destination means every start and one target; reversing all edges turns it into a single-source search from that target. All-pairs asks for every start–target combination and can be solved by repeating a single-source search.

Key Takeaways

  • A distance is a minimum total weight; parents record one route that achieves it.
  • Unreachable vertices have distance ∞.
  • A negative cycle makes a destination’s distance −∞ only when it lies on a route from the source to that destination.
  • Without reachable negative cycles, a shortest simple path uses at most V−1 edges.
  • Follow parents backward and reverse the result to reconstruct a route.

1.3 Improve an estimate by relaxing an edge

A shortest-path algorithm does not begin by knowing the distances. It keeps the best weights found so far and improves them as it discovers better routes. The improvement step is called relaxation.

Start with one known route

Set the source estimate to 0 and every other estimate to ∞. Initially, only the empty path to the source is known. Parents start empty.

For an edge u→v, compare the current estimate for v with a route that first reaches u and then takes that edge:

candidate=d(u)+w(u,v).

If d(u)+w(u,v)<d(v), replace the estimate and its parent together:

d(v)←d(u)+w(u,v),p(v)←u.

A tie needs no update. Using strict improvement also avoids unnecessary parent changes along zero-weight ties.

Work through both outcomes

Suppose u has estimate 7, the edge u→v weighs 3, and v has estimate 12. The candidate is 7+3=10. Since 10 is smaller than 12, v becomes 10 and its parent becomes u. If v already had estimate 9, the candidate 10 would lose and both records would stay unchanged.

If u is unreachable so far, its estimate is ∞ and the edge offers no finite route. In Python, float("inf") + 3 is still infinity. With a fixed-size integer sentinel, adding a weight can overflow; check that the starting estimate is finite before doing the addition.

def relax(u, v, weight, dist, parent):
    if dist[u] == float("inf"):
        return False
    candidate = dist[u] + weight
    if candidate < dist[v]:
        dist[v] = candidate
        parent[v] = u
        return True
    return False

The Boolean result is useful when an algorithm needs to know whether a full pass changed anything.

Understand what an estimate guarantees

Every finite estimate is the weight of an actual route found from the source. Therefore it cannot be below the true minimum:

d(v)≥δ(s,v).

Relaxation only lowers estimates. Once an estimate reaches the true finite distance, later relaxations cannot push it lower. This is the safety of relaxation; it does not say that every early estimate is final.

The triangle inequality for shortest paths says:

δ(s,v)≤δ(s,u)+w(u,v).

The best route to v cannot be heavier than a particular route through u. An edge with d(v)>d(u)+w(u,v) still offers an improvement. After the usual initialization, if no edge offers an improvement, all estimates are exact. If a negative cycle is reachable, some edge keeps offering another improvement.

Give the improvement a useful order

One arbitrary scan may use an old estimate for u and miss a route discovered later in the scan. DAG relaxation prevents this by processing vertices in topological order. Dijkstra processes the smallest unfinished estimate. Bellman–Ford scans all edges in repeated rounds. Floyd–Warshall uses a related improvement for every pair of vertices in a matrix.

Forgetting to update a parent when a distance improves leaves the numbers and reconstructed route out of sync. Treat the distance and its parent as one record whenever a relaxation succeeds.

Key Takeaways

  • Relax u→v when d(u)+w(u,v)<d(v), updating the estimate and parent together.
  • Finite estimates are actual route weights and never fall below the true distance.
  • An unreachable starting vertex cannot offer a finite improvement.
  • No relaxable edge after standard initialization means the estimates are exact.
  • Edge order determines whether a single pass is enough or more passes are needed.
  • Guard integer infinity sentinels before adding weights.
2

Find shortest and longest paths in directed acyclic graphs

Acyclic structure gives a useful processing order: every predecessor can be handled before the vertex that depends on it. Use that order to find shortest paths in linear time, including paths with negative edges. Then reverse the optimization to find longest paths and project completion times, where parallel work makes the slowest chain of dependencies determine the earliest possible finish.

2.1 Process a DAG in dependency order

In a directed acyclic graph, or DAG, no route can return to a vertex it has already visited. A topological order places every edge's starting vertex before its ending vertex. That order gives relaxation all the information it needs in one pass.

Find the order before computing distances

Compute a topological order using Kahn's algorithm or decreasing DFS finishing times. Set the source estimate to 0 and every other estimate to ∞. Visit vertices in that order and relax every outgoing edge of the current vertex.

def dag_distances(graph, order, source):
    dist = {v: float("inf") for v in graph}
    parent = {}
    dist[source] = 0
    for u in order:
        if dist[u] == float("inf"):
            continue
        for v, weight in graph[u]:
            candidate = dist[u] + weight
            if candidate < dist[v]:
                dist[v] = candidate
                parent[v] = u
    return dist, parent

Here order must contain a valid topological ordering of the whole graph. A directed cycle prevents such an order, so this method requires a DAG.

Trace the improvements

Use source A, order A, B, C, D, E, and edges A→B (3), A→C (6), B→C (−2), B→D (4), C→D (1), C→E (5), and D→E (−3).

Vertex processedImprovements made
AB becomes 3; C becomes 6
BC becomes 1; D becomes 7
CD becomes 2; E becomes 6
DE becomes −1
ENo outgoing edges

For example, processing B uses 3−2=1 to improve C. Processing D later uses 2−3=−1 to improve E. The final path to E is A→B→C→D→E, with weight −1.

Alphabetical order happens to work here, but its role is accidental. The order A, C, B, D, E would process C with estimate 6 before B improves it to 1. One pass would then leave D at 7 and E at 4. Computing a topological order avoids that lost propagation.

Why one pass is enough

Every possible predecessor of v appears before v. When v is processed, the incoming edges have already offered their best candidates. On a shortest path, its predecessor u already has its final distance, so relaxing u→v supplies the shortest route to v. Relaxation is safe, so it cannot produce anything smaller than that distance.

This is also a dynamic program. Keep the base case d(s)=0. For any other vertex, take the minimum of d(u)+w(u,v) over its incoming edges. If there are no finite candidates, the result is ∞. Topological order evaluates each dependency before the value that needs it.

Topological sorting takes O(V+E) time. The distance pass visits V vertices and relaxes E edges once, so the total stays O(V+E). Negative edges cause no extra work: a DAG cannot contain a negative cycle. Vertices before the source in the order are unreachable from it and retain ∞.

Key Takeaways

  • A topological order places every predecessor before the vertex that needs its distance.
  • Initialize the source to 0, then relax outgoing edges once in topological order.
  • DAG relaxation accepts positive, zero, and negative weights.
  • Topological sorting plus relaxation takes O(V+E) time.
  • The recurrence has a separate source base case; unreachable vertices retain ∞.

2.2 Use a longest path to schedule a project

Shortest paths minimize a sum. Some DAG problems need the largest sum instead. Project scheduling is one: work can run in parallel, but every chain of dependent jobs must finish before the whole project can end.

Reverse the comparison

For longest paths in a DAG, set the source to 0 and all other estimates to −∞. Process vertices in topological order and replace an estimate when the candidate is larger. An unreachable vertex stays −∞ in this longest-path computation.

Equivalently, negate every edge weight, run shortest-path DAG relaxation, and negate each result. A route of original weight 9 becomes −9, so the largest original sum becomes the smallest transformed sum. The graph remains acyclic.

This does not give an efficient longest-simple-path method for a general graph. Negating a cycle of positive total weight creates a negative cycle. The longest simple path problem in general graphs is NP-hard, and no polynomial-time algorithm for it is known.

Calculate earliest finishes

Assume any number of jobs can run in parallel and jobs wait only for their prerequisites. A job starts when its slowest prerequisite finishes:

earliest finish=duration+max⁡(prerequisite finishes).

Use 0 when a job has no prerequisites. Consider this project:

JobDurationPrerequisitesEarliest finish
Design3 daysNone3
Backend5 daysDesign8
Frontend4 daysDesign7
Docs1 dayDesign4
Testing2 daysBackend, Frontend10
Release1 dayTesting, Docs11

Testing waits until day 8 because Backend finishes later than Frontend. It then takes 2 days, finishing at day 10. Release waits for both Testing and Docs, so it finishes at max⁡(10,4)+1=11 days.

Adding all durations gives 16 days, which ignores parallel work. Choosing the quickest chain also fails: completion requires the longest dependency chain to finish.

Identify the critical jobs and slack

Design→Backend→Testing→Release totals 3+5+2+1=11 days. This is a critical path. Its jobs have no spare time: a delay to one delays the project's earliest completion.

Frontend may finish at day 8 without delaying Testing. Its earliest finish is day 7, giving 1 day of slack. Docs may finish at day 10 without delaying Release, giving 6 days of slack. There may be several critical paths if longest chains tie.

Turn the schedule into edges

Give every job a start vertex and an end vertex, joined by an edge weighted with its duration. A prerequisite adds a zero-weight edge from its end to the dependent job's start. Add a source with zero-weight edges to all starts, and zero-weight edges from all ends to a sink.

The source-to-sink longest path now sums the durations of a dependency chain. The split vertices put a job's duration on exactly one edge, while the zero-weight edges enforce the order without adding time.

Key Takeaways

  • Longest paths in a DAG use topological order with maximum updates and initial −∞ estimates.
  • Negating weights converts a DAG longest-path problem into a shortest-path problem.
  • A job’s earliest finish is its duration plus the latest finish among its prerequisites.
  • With unrestricted parallel work, the project length is the longest dependency chain.
  • Critical jobs have no slack; noncritical jobs can tolerate a limited delay.
  • Splitting each job into start and end vertices puts its duration on an edge.
3

Compute shortest paths with Dijkstra's algorithm

Nonnegative edge weights let a search commit to one distance at a time. Follow Dijkstra’s choices, implement the priority queue with Python’s heapq, and connect its work to the graph’s size and density. A small negative-edge counterexample then pinpoints the step that loses its guarantee, including why adding a constant to every edge or simply revisiting vertices does not preserve the usual algorithm.

3.1 Finish the closest vertex with Dijkstra’s algorithm

Dijkstra's algorithm solves single-source shortest paths when every edge weight is nonnegative. Cycles are allowed, and zero-weight edges are allowed. The algorithm repeatedly chooses the smallest unfinished distance estimate and makes it final.

Distinguish discovery from finishing

Initialize the source to 0 and all other estimates to ∞. Every vertex starts unfinished. Choose the unfinished vertex u with the smallest estimate, finish u, and relax all edges leaving it. Repeat until no finite unfinished estimate remains.

A vertex may be discovered long before it is finished. Its estimate can improve while it waits. Finishing it at first discovery would discard those later improvements.

Trace a full search

Use edges S→A (4), S→B (2), B→A (1), A→C (5), B→C (8), B→D (10), C→D (2), C→T (6), and D→T (2). Start at S.

FinishDistanceUpdates to unfinished vertices
S0A=4, B=2
B2A=3, C=10, D=12
A3C=8
C8D=10, T=14
D10T=12
T12None

After finishing B, both A and C have new candidates. The next choice is A with total distance 3, even though C has already been discovered. When A finishes, C improves from 10 to 3+5=8.

The final distances in finishing order are 0, 2, 3, 8, 10, and 12. Each successful improvement also records a parent, giving the path S→B→A→C→D→T to T.

Why the greedy choice is safe

Assume earlier finished vertices have correct distances. Let u be the unfinished vertex with the smallest estimate. Take a shortest route to u and find its first unfinished vertex x. The vertex just before x is finished and has already relaxed its edge into x, supplying the shortest prefix to x.

The remaining edges from x to u have weights at least 0, so continuing the route cannot lower its weight. Since u has the smallest unfinished estimate, x cannot have an estimate below u's. These facts force u's estimate to equal its true distance. This is the greedy step: one choice can be committed without revisiting it.

The nonnegative condition is doing real work here. A negative edge could let a later prefix become cheaper after it crosses that edge.

Compare total estimates across the whole frontier

With S→A (1), S→B (4), and A→C (6), finishing A gives C an estimate of 7. Dijkstra then finishes B at 4, even though B is not a neighbor of A. The choice comes from all unfinished vertices, not from the cheapest next edge out of the current vertex.

BFS uses a first-in, first-out queue and expands hop layers. Dijkstra uses a minimum-priority queue and expands distance order. If every edge weighs 1, these layer orders agree.

For a single target, stop when that target is finished, when its smallest current estimate is selected. Stopping when the target is first discovered can return a route that a later relaxation would improve. Unreachable vertices keep ∞.

Key Takeaways

  • Dijkstra requires every edge weight to be at least 0.
  • Finish the smallest unfinished total estimate, then relax its outgoing edges.
  • Discovery gives a tentative estimate; finishing makes it final.
  • Nonnegative remaining edges justify the greedy choice.
  • A single-target search may stop when the target is finished.

3.2 Implement the priority queue and account for its cost

A minimum-priority queue finds the next vertex without scanning every unfinished estimate. Python's heapq provides insert and extract-min, but no decrease-key operation. Lazy deletion handles improvements by leaving old entries in the heap.

Push improvements and skip old entries

Store a pair containing a distance and a vertex. Each successful relaxation pushes a new pair. An older pair becomes stale if its distance exceeds the vertex's current estimate.

import heapq

def dijkstra(graph, source):
    dist = {v: float("inf") for v in graph}
    parent = {}
    dist[source] = 0
    queue = [(0, source)]
    while queue:
        du, u = heapq.heappop(queue)
        if du > dist[u]:
            continue
        for v, weight in graph[u]:
            candidate = du + weight
            if candidate < dist[v]:
                dist[v] = candidate
                parent[v] = u
                heapq.heappush(queue, (candidate, v))
    return dist, parent

The input has nonnegative weights, includes every vertex as a dictionary key, and uses comparable labels such as strings. Finishing occurs on an up-to-date pop. Marking a vertex finished when it is pushed would prevent a later better route from taking effect.

For a single target, the early-return check belongs after the stale check. For path reconstruction, follow parent backward from the target and reverse the list. First check that its distance is finite.

See why old entries remain

In the graph S→A (4), S→B (2), B→A (1), A→C (5), B→C (8), B→D (10), C→D (2), C→T (6), D→T (2), A enters the heap with 4 and later with 3. The pair (3, "A") is processed first. When (4, "A") appears, dist["A"] is 3, so the old pair is skipped.

The search makes 10 pushes: one for S and nine for successful edge relaxations. Four pops are stale: A at 4, C at 10, D at 12, and T at 14. Removing the stale check repeats scans of outgoing edges.

Count the heap operations

With nonnegative weights, each reachable vertex's outgoing edges are scanned once after an up-to-date pop. Each successful edge relaxation makes at most one push, so a lazy heap can hold O(E) entries and uses O(V+E) extra space including distances and parents.

For graphs without parallel edges, E≤V2, so log⁡E=O(log⁡V). Including initialization and heap work gives O((V+E)log⁡V) time. When all vertices are reachable, it is often written O(Elog⁡V).

Queue choiceTotal timeMain tradeoff
Array scanO(V2)Useful on dense graphs
Binary heapO((V+E)log⁡V)Practical on sparse graphs
Fibonacci heapO(E+Vlog⁡V)Better theoretical decrease-key cost, more overhead

Python compares the second tuple field when distances tie. Custom vertex objects may not support ordering. A unique increasing counter placed between distance and vertex, as (distance, counter, vertex), resolves ties without comparing the objects.

Key Takeaways

  • Lazy deletion pushes a new entry for each strict improvement and skips stale pops.
  • A vertex finishes when its current distance is popped, not when it is inserted.
  • A lazy heap may store O(E) entries.
  • Binary-heap Dijkstra takes O((V+E)log⁡V) on a graph without parallel edges.
  • An array can be preferable on dense graphs; Fibonacci heaps improve the theoretical bound.
  • Use a unique counter to break heap ties between noncomparable vertex objects.

3.3 Locate the failure caused by a negative edge

Nonnegative edges justify Dijkstra's decision to finish the smallest current estimate. A negative edge can break that decision even when no negative cycle exists.

Build a counterexample

Take edges S→A (2), S→B (5), and B→A (−4). After finishing S, the estimates are A=2 and B=5. Dijkstra chooses A first because 2 is smaller than 5.

The true best route to A is S→B→A, whose weight is 5−4=1. That route is discovered only after B is processed. A has already been declared finished at 2. A version that refuses updates to finished vertices therefore returns the wrong distance.

Add A→C (1). Processing A at 2 offers C the estimate 3, which is also finished before B at 5. The true route S→B→A→C weighs 5−4+1=2. One early wrong commitment can spread to downstream vertices.

Identify the broken reasoning step

The prefix S→B weighs more than the current route to A. With nonnegative edges, continuing from B cannot lower that prefix. Here the −4 edge does lower it. The smallest current estimate no longer certifies the smallest possible complete route.

A negative edge does not force every run to return a wrong answer. It means Dijkstra's correctness guarantee no longer applies. Zero-weight edges are different: continuing over them preserves a prefix weight, so the proof still works.

Why adding a constant changes the problem

Adding 4 to every edge in the three-edge graph gives S→A (6), S→B (9), and B→A (0). Dijkstra can solve this transformed graph, but its answer chooses S→A with weight 6. The two-edge route S→B→A weighs 9 and loses.

The original two-edge route weighed 1 and won against the direct edge at 2. The transformation added 4 once to the direct route and twice to the two-edge route. In general, a k-edge path gains 4k. Different edge counts receive different changes, so route rankings need not survive.

Why revisiting is a different algorithm

The lazy heap loop can allow an improved vertex to be processed again. On this acyclic counterexample it can eventually repair A and C, provided it does not return early. That behavior is not Dijkstra's finish-once argument. With negative edges, the number of repeated improvements can be exponential in the worst case. A reachable negative cycle can keep the loop running indefinitely.

Choose the algorithm from the graph's structure and weights:

InputCorrect single-source choice
DAG, including negative edgesTopological relaxation
General graph, all weights at least 0Dijkstra's algorithm
General graph with negative edgesBellman–Ford with a cycle check

For the counterexample, topological order S, B, A, C solves the distances directly.

Key Takeaways

  • A later negative edge can improve a vertex after Dijkstra has finished it.
  • A negative edge removes the guarantee; it need not make every particular run fail.
  • Adding a constant per edge can change which path is shortest.
  • Reprocessing improved vertices loses Dijkstra’s time bound and can fail to terminate on a reachable negative cycle.
  • Use DAG relaxation for acyclic inputs and Bellman–Ford for general inputs with negative edges.
4

Handle negative weights with Bellman–Ford

When negative edges may occur in a graph with cycles, a distance estimate must remain open to later improvement. Bellman–Ford propagates routes through repeated edge scans, with a simple-path edge bound controlling the work. An extra round separates finite distances from the influence of a reachable negative cycle. Parent pointers and graph traversal then locate that cycle and identify its affected destinations.

4.1 Propagate routes through Bellman–Ford rounds

Bellman–Ford allows negative edges by keeping estimates open to improvement. It repeatedly scans every edge instead of declaring the smallest unfinished estimate final. A bound on the length of a simple shortest path tells it how many rounds are enough.

Scan every edge in each round

Set the source estimate to 0 and all others to ∞. Relax every edge in a fixed order, then repeat for at most V−1 rounds. Each update changes both the estimate and its parent.

Use source S, vertices S, A, B, C, and this edge order: A→C (3), B→A (−2), S→A (4), S→B (5).

End of roundSABC
Initialization0∞∞∞
1045∞
20357
30356

In round 1, the first two edges start at vertices that still have infinite estimates. The last two edges discover A and B. In round 2, A first gives C the candidate 7; then B lowers A to 5−2=3. Round 3 propagates that improvement to C, giving 3+3=6.

Know what a round guarantees

After round k, each estimate is at most the weight of the best source route using at most k edges. In-place updates may propagate farther within one round when the edge order is favorable. A round guarantees at least one more edge of propagation; it does not limit progress to exactly one edge.

With no reachable negative cycle, every reachable vertex has a simple shortest path using at most V−1 edges. After that many full rounds, those routes have all propagated. Relaxation never undershoots the true distance, so the estimates are exact.

For the order S→A, S→B, B→A, A→C, all final values appear during round 1. Reversing useful edges can require more rounds, but the final distances stay the same.

Stop only after a full unchanged round
for _ in range(len(vertices) - 1):
    changed = False
    for u, v, weight in edges:
        if dist[u] == float("inf"):
            continue
        candidate = dist[u] + weight
        if candidate < dist[v]:
            dist[v] = candidate
            parent[v] = u
            changed = True
    if not changed:
        break

If a whole round changes nothing, every edge already passes the relaxation test. Running the same edges again cannot produce a new value. Seeing only one unchanged edge or one apparently settled vertex is insufficient to stop the algorithm.

Connect the rounds to dynamic programming

Let dk(v) mean the best weight with at most k edges. Its recurrence compares keeping the previous value with extending a previous-layer route by one edge:

dk(v)=min⁡(dk−1(v),min⁡(u,v)∈E{dk−1(u)+w(u,v)}).

Using separate previous and next arrays computes this exact layered recurrence. The in-place scan can move faster within a round. Both reach final finite distances after V−1 rounds when no negative cycle is reachable.

There are E relaxation checks per round: O(VE) time, plus initialization, and O(V) extra space for estimates and parents. A queue of changed vertices can reduce practical work but retains the O(VE) worst case. Before reporting distances, perform the extra negative-cycle check.

Key Takeaways

  • Bellman–Ford relaxes every edge for at most V−1 full rounds.
  • In-place edge order changes progress within a round, not the final finite distances.
  • The V−1 bound comes from the maximum edge count of a simple path.
  • A full unchanged round permits early stopping.
  • The standard worst-case bound is O(VE) time and O(V) extra space.
  • Finite estimates need a negative-cycle check before they are reported as distances.

4.2 Detect a negative cycle and report the affected destinations

Negative edges can belong to perfectly finite shortest paths. A reachable negative cycle is different: its repeated use makes some route weights decrease without bound. Bellman–Ford distinguishes these cases with one extra round.

Perform the check round

After V−1 rounds, try relaxing every edge again. Any strict improvement proves that a negative cycle is reachable from the source. Without such a cycle, a simple shortest route would already have propagated within V−1 rounds.

Add C→B (−5) to edges A→C (3), B→A (−2), S→A (4), S→B (5), keeping that edge order and putting C→B last. The cycle B→A→C→B weighs −2+3−5=−4.

After three rounds, the estimates are A=0, B=1, C=6. In the check round, A→C lowers C to 3, B→A lowers A to −1, and C→B can lower B again. These remaining improvements expose the reachable negative cycle; the finite numbers left in the array are not its affected vertices' distances.

Recover an actual cycle

Record parents during the check round, and choose a vertex x whose estimate decreased. Follow its parent V times. This skips any downstream tail and reaches a vertex on a negative cycle. Starting there, continue following parents until the same vertex appears again.

Parents point backward along graph edges. Reverse the collected cycle to display it in the direction of travel, then verify that its edge weights sum to a negative number. A vertex improved in the check round may itself lie after the cycle, which is why the initial V parent steps are necessary.

Mark where the answer is negative infinity

Run BFS or DFS forward from all vertices improved during the check round. Mark every vertex reached as having distance −∞. These are the destinations that can be reached after looping around a source-reachable negative cycle.

Vertices unreachable from the source keep ∞. A source-reachable branch that the negative cycle cannot reach can still have finite distances. Detecting one negative cycle does not make every vertex's distance −∞.

Bellman–Ford from s sees only cycles reachable from s. To detect a negative cycle anywhere, add a new source q with zero-weight edges to every original vertex and run Bellman–Ford from q. Now every component is reachable.

Turn exchange products into path sums

For exchange rates, a loop with a rate product greater than 1 returns more money than it starts with. Rates X→Y 0.9, Y→Z 0.8, and Z→X 1.5 have product 0.9×0.8×1.5=1.08, an 8% gain.

Assign each trade the weight −ln⁡(rate). Logarithms turn multiplication into addition, and the minus sign turns profitable products into negative sums:

−ln⁡(0.9)−ln⁡(0.8)−ln⁡(1.5)=−ln⁡(1.08)≈−0.077.

Bellman–Ford can detect the resulting negative cycle and its parent pointers can recover the loop of trades. If an undirected negative edge is represented by two opposite directed edges, traversing it out and back already creates a negative cycle.

Key Takeaways

  • An improvement in the extra round proves a source-reachable negative cycle.
  • Follow V parents before collecting a cycle, then reverse the parent order.
  • Only vertices downstream of a source-reachable negative cycle have distance −∞.
  • A zero-edge super-source makes whole-graph cycle detection possible.
  • Trade weights −ln⁡(rate) turn profitable exchange loops into negative cycles.
5

Compute all-pairs distances and apply shortest paths to routing

Some applications need an entire table of distances; others need one carefully chosen search on a transformed map. Compare repeated single-source searches with Floyd–Warshall and Johnson’s algorithm, then turn route-planning requirements into directions, costs, and starting states. Choosing the right graph model can save many searches while making the computed distances match the trips people actually want to take.

5.1 Choose an all-pairs distance method

All-pairs shortest paths asks for a distance for every ordered pair of vertices. The usual answer is a V-by-V matrix, so writing the full answer already requires Θ(V2) entries.

Repeat a single-source method

Running from each vertex gives these bounds:

InputRepeated methodTotal time
DAGDAG relaxationO(V(V+E))
Nonnegative weightsBinary-heap DijkstraO(V(V+E)log⁡V)
General weightsBellman–FordO(V2E)

The last bound becomes O(V4) on a dense graph. A matrix-based dynamic program avoids that extra factor.

Allow intermediate vertices one at a time

Floyd–Warshall starts with direct edges, zero diagonal entries, and ∞ for missing connections. With parallel edges, keep the lightest direct edge; a negative self-loop must remain negative for the cycle test.

Without negative cycles, let dk(i,j) be the lightest route whose intermediate vertices come from 1 through k. A best route either avoids k or passes through k:

dk(i,j)=min⁡(dk−1(i,j),dk−1(i,k)+dk−1(k,j)).

The in-place implementation keeps k outermost:

for k in range(n):
    for i in range(n):
        for j in range(n):
            dist[i][j] = min(dist[i][j],
                             dist[i][k] + dist[k][j])

For edges 1→2 (4), 1→3 (7), 2→3 (1), and 3→1 (2), allowing vertex 1 creates 3→1→2 with weight 6. Allowing vertex 2 improves 1→3 to 5. Allowing vertex 3 creates 2→3→1 with weight 3. The final rows are (0,4,5), (3,0,1), and (2,6,0).

Moving k inside the other loops loses the guarantee that all routes through earlier allowed intermediates are ready. The algorithm takes O(V3) time and O(V2) space. It permits negative edges. A negative final diagonal entry detects a negative cycle; pairs able to travel through such a cycle have distance −∞, not the finite matrix entries.

Reweight a sparse graph with Johnson's algorithm

Add a source q with zero-weight edges to all vertices. Bellman–Ford gives potentials h(v)=δ(q,v) or detects a negative cycle. Reweight every edge:

w′(u,v)=w(u,v)+h(u)−h(v).

These weights are nonnegative. Along any path, the potential terms cancel except at the endpoints, so all s-to-t routes change by the same amount h(s)−h(t). Run Dijkstra from every vertex, then recover original distances with δ(u,v)=δ′(u,v)−h(u)+h(v).

For A→C (3), B→A (−2), S→A (4), S→B (5), the potentials are S=0, A=−2, B=0, C=0. New weights are 1, 0, 6, and 5. The two S-to-C routes still weigh 6 and 7 because their endpoint potentials are equal.

Johnson takes O(V(V+E)log⁡V) with a binary heap, or O(V2log⁡V+VE) with a Fibonacci heap. Dense graphs often favor Floyd–Warshall; sparse nonnegative graphs favor repeated Dijkstra, and sparse graphs with negative edges favor Johnson.

Key Takeaways

  • All-pairs output has Θ(V2) entries.
  • Floyd–Warshall allows one more intermediate vertex in each outer iteration.
  • Keep k outermost for O(V3) time and O(V2) space.
  • A negative diagonal detects a negative cycle; affected pairs need −∞.
  • Johnson uses Bellman–Ford potentials to make weights nonnegative without changing route rankings.
  • Undo reweighting with δ(u,v)=δ′(u,v)−h(u)+h(v).
  • Use graph density and weight signs to choose the all-pairs method.

5.2 Build a routing graph that answers the right question

A correct shortest-path search solves the graph it receives. Useful route planning starts by deciding what each vertex, edge, and weight means, and which direction each requested trip takes.

Choose an algorithm from the input
Graph and weightsSingle-source methodTime
Unweighted or equal positive weightsBFSO(V+E)
DAG with any weightsTopological relaxationO(V+E)
General graph, nonnegative weightsBinary-heap DijkstraO((V+E)log⁡V)
General graph with negative weightsBellman–Ford and cycle checkO(VE)

Acyclic structure is useful even when negative weights are present. When the graph can contain cycles, use the weight signs to decide whether Dijkstra's guarantee applies.

Define the route objective

For a road map, intersections are vertices and road segments are edges. A one-way road needs one arrow. A two-way road needs both directions, potentially with different times if travel conditions differ. Road lengths in kilometers and expected times in minutes are nonnegative, so Dijkstra is a standard choice.

From home to a station, a ring-road route is 12 km and takes 14 minutes. A route through the center is 8 km and takes 20 minutes. Distance weights select the center; time weights select the ring road. "Best route" becomes precise only after selecting the weight.

If time and a fee both matter, define a combined additive score, such as minutes plus fee multiplied by a chosen minutes-per-money factor. That factor expresses the tradeoff. Mixing the numbers without a stated conversion gives the sum no clear meaning. Remove roads that must be avoided.

Reverse edges for trips toward a destination

To compute travel time from every neighborhood to one hospital, reverse every edge and search once from the hospital. Every original route into the hospital corresponds to a reversed route outward from it with the same total weight.

Searching outward from the hospital on the original one-way map answers a different question: travel from the hospital. Direction reversal is essential even when the distances happen to agree on a two-way example.

For the nearest charging station from every intersection, reverse the map and initialize every station at distance 0 in one Dijkstra run. The result at an intersection is the minimum time to any station in the original map. This is equivalent to adding one super-source with zero-weight edges to the stations. On the original graph, the same multi-source search would measure travel outward from stations.

Put a cost at a place onto an edge

A fixed transfer cost can be represented by splitting a vertex into arrival and departure copies. Join them with an edge weighted by the transfer time, such as 3 minutes. Incoming roads enter the arrival copy; outgoing roads leave the departure copy. A route that makes the transfer crosses the internal edge once.

Adding a cost to every outgoing edge is another representation for a cost charged on departure. Check source and destination treatment: a destination with no departure would not pay that cost. Split vertices make the charging event explicit.

The same modeling choices cover network delay in milliseconds, project completion through a longest DAG path, and arbitrage through transformed rates. Large map planners add preprocessing to accelerate queries while preserving the shortest-path distances of their weighted graph.

Key Takeaways

  • Check equal weights, acyclic structure, and weight signs before choosing the algorithm.
  • Choose one additive objective and keep its units consistent.
  • Reverse a directed graph to answer many-start, one-destination queries with one search.
  • Use zero initial estimates at several stations for a multi-source search.
  • A fixed cost at a place can be moved onto an internal arrival-to-departure edge.
  • Combining time and fees requires an explicit conversion factor.

Shortest Path Algorithms examples

5 Walkthroughs

1

From road costs to distance estimates

14 steps
Build a weighted route model, interpret its possible distance values, and perform the relaxation update.
  1. 1
    IntroductionGive a route a measurable cost

    A delivery route may save distance while taking more time. A weighted graph lets you state exactly what the search should minimize.

    Start with the edges and their units, then separate the value of the best route from the route itself. Finally, improve a tentative answer using one edge. That small update will support every single-source algorithm that follows.

  2. 2
    ExplanationStore each allowed move

    A weighted edge records a direction and a cost. An edge P→Q (6) allows travel from P to Q at cost 6. It says nothing about a return trip.

    An adjacency list keeps the neighbor and weight together, such as "P": [("Q", 6)]. A two-way connection needs a second entry from Q to P. Include an empty list for a vertex with no outgoing edges so it remains part of the graph.

  3. 3
    ExampleCompare a short route with a light route

    Suppose the edges are S→P (10 minutes), S→Q (3 minutes), and Q→P (4 minutes).

    The direct route has one edge and costs 10 minutes. The two-edge route S→Q→P costs 3+4=7 minutes. A BFS search prefers the one-edge route because it minimizes hops. A weighted shortest-path search must compare the sums and choose the 7-minute route.

  4. 4
    ChallengeChoose a missing-edge marker

    A matrix stores travel times. Some real connections take 0 minutes. Could 0 also mark a missing connection? Explain your choice of marker.

    ---reveal---

    No: the same entry would then describe two different situations. Use ∞ or another separate marker for a missing edge and keep 0 for a free connection. Changing a real zero to a positive number would alter the route problem.

  5. 5
    ExplanationRead a distance value

    The distance δ(s,t) is the minimum total weight from s to t. A reachable route can have a finite distance, including a negative one.

    If no route reaches t, the distance is ∞. A distance of −∞ means routes to t can be made lighter without limit by looping around a reachable negative cycle before continuing to t. It is a statement about the absence of a minimum.

  6. 6
    ExampleCheck both directions of reachability

    Let S reach B, and let B→C (−4), C→B (1), and C→T (5). Each B→C→B lap weighs −3.

    B, C, and T have distance −∞ from S: another lap can always precede the final trip to them. If S also has an edge to U, but the cycle cannot reach U, that branch may still have a finite distance. Reachability from the same source does not make every branch affected.

  7. 7
    Key InsightRemove an unnecessary cycle

    Without a reachable negative cycle, any cycle on a source route has weight at least 0. Removing it cannot increase the total.

    A shortest route can therefore be chosen with no repeated vertices: a simple path. It visits at most V vertices and uses at most V−1 edges. This is a bound on a useful shortest route, even when other equally light routes include zero-weight cycles.

  8. 8
    ChallengeTurn parents into a forward route

    From source S, the final parent records are p(T)=M, p(M)=L, and p(L)=S. What route reaches T? Would another parent choice necessarily mean a wrong distance?

    ---reveal---

    Following parents gives T, M, L, S. Reverse that sequence to get S→L→M→T. A different parent can still be correct when two routes tie in weight; the selected shortest-path tree need not be unique.

  9. 9
    ExplanationInitialize what is actually known

    Set d(s)=0 because the empty route to the source costs nothing. Set every other estimate to ∞, and leave parents empty.

    Each finite estimate will represent a route already found. That makes it an upper bound on the true shortest distance: a discovered route may be heavier than the best route, but cannot be lighter than the minimum. Initializing all vertices to 0 would invent free routes to them.

  10. 10
    ExampleOffer a new route through an edge

    Suppose d(L)=5, the edge L→M weighs 4, and d(M)=12. Reaching L and continuing to M offers the candidate 5+4=9.

    Because 9 is smaller than 12, set d(M)=9 and p(M)=L. These two changes belong together: the number records the improved weight, and the parent records the last step of the route that produced it.

  11. 11
    ChallengeDecide whether to change a record

    Now d(L)=5, L→M weighs 4, and d(M)=8. What should relaxing L→M change?

    ---reveal---

    Nothing. The candidate 9 loses to the known route at 8, so both M’s estimate and its parent stay unchanged. Relaxation accepts only a strictly smaller candidate. It does not replace a good route merely because another incoming edge has just been examined.

  12. 12
    TipDo not add to an integer infinity marker

    An edge out of an unreachable vertex supplies no finite source route. Skip that edge while its starting estimate is infinite.

    Python’s float("inf") stays infinite when a finite weight is added. A largest-integer marker can overflow in a fixed-size integer type, creating a false small candidate. The reachability check must come before the addition, not after the corrupted value appears.

  13. 13
    ChallengeDiagnose a premature answer

    An edge scan begins with d(S)=0 and all other estimates ∞. It checks P→T (2) before S→P (6), then stops. What is wrong with its answer for T?

    ---reveal---

    P was still unreachable when P→T was checked, so T stays ∞. Later in the scan, S→P makes P=6, but that improvement never reaches T. The route S→P→T weighs 8. A correct algorithm needs a useful edge order or further relaxation rounds.

  14. 14
    RecapConnect the records to the graph

    The graph supplies legal moves and additive costs. A distance can be finite, unreachable, or unbounded below; parents recover one chosen route when a finite shortest route exists.

    To check an improvement, add the starting estimate and edge weight, compare with the destination estimate, and change its parent with its distance. The next problem is deciding an order that makes those updates finish efficiently.

2

Solve routes and schedules in a DAG

13 steps
Use one topological pass for weighted routes, then switch to longest paths to find a project’s earliest completion.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionLet the dependencies choose the order
  2. 2
    ExplanationPut predecessors first
  3. 3
    ExampleStart the DAG trace
  4. 4
    ExampleCarry the improvement forward
  5. 5
    ChallengeTest an unsafe processing order
  6. 6
    Key InsightCount each dependency once
  7. 7
    ConnectionChange minimum into maximum
  8. 8
    ExampleRead a parallel project
  9. 9
    ExampleWait for the latest prerequisite
  10. 10
    ChallengeFind the available slack
  11. 11
    ExplanationMove a job duration onto an edge
  12. 12
    ChallengeExplain the scheduling choice
  13. 13
    RecapReuse the order, choose the right comparison
3

Trace and implement Dijkstra safely

15 steps
Follow minimum-distance choices, inspect lazy heap entries, and locate the exact failure caused by a negative edge.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionCommit only when a distance is ready
  2. 2
    ExplanationChoose the smallest unfinished total
  3. 3
    ExampleDiscover the first candidates
  4. 4
    ChallengeChoose the next unfinished vertex
  5. 5
    ExampleFinish the target
  6. 6
    Key InsightFind where nonnegative weights matter
  7. 7
    ExplanationLeave old heap entries for later
  8. 8
    ExampleSpot a stale pop in the trace
  9. 9
    ChallengePlace the target test correctly
  10. 10
    TipHandle ties and count heap work
  11. 11
    ExampleA negative edge arrives too late
  12. 12
    ChallengeCheck the constant-shift repair
  13. 13
    ExplanationRevisiting loses the finish-once guarantee
  14. 14
    ChallengeChoose for a changing graph
  15. 15
    RecapCheck the guarantee before trusting the heap
4

Use Bellman–Ford to find distances or a negative cycle

14 steps
Trace repeated scans, understand the round bound, and follow a negative cycle’s effect through the graph.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionKeep a route open to later improvement
  2. 2
    ExplanationSet the round budget
  3. 3
    ExampleRound 1 discovers the starting branches
  4. 4
    ExampleRound 2 improves an earlier route
  5. 5
    ChallengeComplete the third round
  6. 6
    Key InsightSeparate in-place rounds from layers
  7. 7
    TipStop after a whole quiet round
  8. 8
    ExplanationAsk whether any improvement remains
  9. 9
    ExampleAdd a loop that never settles
  10. 10
    ExplanationEnter the cycle before collecting it
  11. 11
    ChallengeMark only the affected destinations
  12. 12
    ConnectionDetect profit by adding logarithms
  13. 13
    ChallengeCheck an entire exchange graph
  14. 14
    RecapReport a finished answer in either case
5

Build all-pairs answers and directed routing models

16 steps
Update a distance matrix, apply Johnson’s potentials, and transform routing queries into the right searches.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionChoose what the output must answer
  2. 2
    ExplanationCount the distance table
  3. 3
    ExampleInitialize a Floyd–Warshall matrix
  4. 4
    ExampleAllow the first two intermediate vertices
  5. 5
    ChallengeFinish the matrix stages
  6. 6
    Key InsightInspect the diagonal before reporting distances
  7. 7
    ExplanationMake sparse negative-edge searches nonnegative
  8. 8
    ExampleCancel the interior potential terms
  9. 9
    ChallengeSelect an all-pairs strategy
  10. 10
    ExplanationLet the objective pick the weights
  11. 11
    ExampleSearch toward a destination
  12. 12
    ChallengeChoose the direction for nearest stations
  13. 13
    ExampleCharge a transfer exactly where it occurs
  14. 14
    TipUse the strongest input structure
  15. 15
    ChallengeCombine the model with the algorithm
  16. 16
    RecapCheck endpoints, weights, and output size

Shortest Path Algorithms practice questions

50 Practice Questions in 5 sets

Set 1: Trace DAG routes and Dijkstra’s choices10 Practice Questions

Question 1 of 10

For edges P→Q, P→T, and Q→T, what is a valid topological order?
  1. Q, P, T
  2. P, Q, T
  3. P, T, Q
  4. T, Q, P
Show answerHide answer
Answer: B
P must precede both destinations, and Q must precede T, so P, Q, T satisfies every edge. P, T, Q respects the edges out of P but reverses Q→T, which is enough to invalidate the whole order.

Question 2 of 10

A DAG has R→P (7), R→Q (12), P→Q (−5), and Q→T (4). What distance does topological relaxation find from R to T?
  1. 16
  2. 11
  3. 2
  4. 6
Show answerHide answer
Answer: D
Processing R first gives P=7 and Q=12. Processing P lowers Q to 7−5=2, and processing Q then gives T=2 + 4 = 6. The tempting value 16 uses R→Q→T and misses the improvement through P before Q’s outgoing edge is scanned.

Question 3 of 10

Setup takes 4 days. Cut takes 6 days after Setup, and Coat takes 3 days after Setup. Pack takes 2 days after both. With unrestricted parallel work, when can Pack finish?
  1. Day 12
  2. Day 15
  3. Day 9
  4. Day 10
Show answerHide answer
Answer: A
Setup finishes at day 4, so Cut finishes at day 10 and Coat at day 7. Pack waits for the later finish, starts on day 10, and takes 2 more days, giving day 12. Adding all durations gives 15 and incorrectly forces the two independent branches to run in sequence.

Question 4 of 10

In a nonnegative graph, the unfinished estimates are P=9, Q=4, and T=6. Which vertex does Dijkstra finish next?
  1. P
  2. T
  3. Q
  4. The most recently discovered vertex
Show answerHide answer
Answer: C
Q has the smallest total source-distance estimate, 4, so it is the next vertex finished. Choosing T because it is a desired target would bypass the minimum rule; an unfinished target is not yet certified just because its estimate is finite.

Question 5 of 10

From R, the edges are R→P (11), R→Q (3), Q→P (2), Q→T (9), and P→T (4). What is the finishing order in Dijkstra’s algorithm?
  1. R, Q, P, T
  2. R, P, Q, T
  3. R, Q, T, P
  4. R, T, Q, P
Show answerHide answer
Answer: A
After R, the estimates are Q=3 and P=11. Finishing Q lowers P to 5 and discovers T at 12; finishing P then lowers T to 9, giving order R, Q, P, T. The order R, P, Q, T follows first discovery instead of comparing current total estimates and would finish P too early.

Question 6 of 10

A nonnegative search discovers target T at 15. An unfinished vertex P has estimate 6 and an edge P→T of weight 4. What is the earliest safe stopping event for T?
  1. T is first inserted with its estimate of 15.
  2. T is removed with its current minimum estimate.
  3. P is inserted, without scanning its outgoing edges.
  4. Any vertex with estimate at least 6 is removed.
Show answerHide answer
Answer: B
P is unfinished at cost 6 and can offer T a route of 6+4=10, so T’s first-discovered value 15 can still improve. Wait until T is removed with its current minimum estimate after stale entries are rejected. Stopping when P is inserted is also premature because its outgoing edge has not yet propagated that candidate.

Question 7 of 10

A 5-day job can start on day 3 and must finish by day 11 to avoid delaying the project. How much slack does it have?
  1. 8 days
  2. 5 days
  3. 2 days
  4. 3 days
Show answerHide answer
Answer: D
Starting on day 3 with a duration of 5 gives an earliest finish at day 8. Finishing by day 11 therefore allows 11−8=3 days of delay without changing project completion. The value 8 is the job’s finish date, not its slack; slack is the gap between the earliest and latest permitted timings.

Question 8 of 10

All edges have weight 1. How do BFS and Dijkstra compare for minimum source distances?
  1. Dijkstra finds lighter paths in a layer.
  2. They produce the same distance layers.
  3. BFS is correct only on acyclic graphs.
  4. Dijkstra rescales each layer’s distance.
Show answerHide answer
Answer: B
A route’s total weight equals its edge count when every edge weighs 1, so both searches group vertices by the same distance layers. Cycles do not invalidate BFS on an unweighted graph; a visited rule prevents repeated discovery.

Question 9 of 10

A one-pass distance routine uses order R, Q, P, T on edges R→P (2), R→Q (9), P→Q (1), and Q→T (2). It scans outgoing edges once per vertex. What does it report for T, and what is the true distance?
  1. Reported 5; true 5.
  2. Reported 11; true 3.
  3. Reported 11; true 5.
  4. Reported 9; true 5.
Show answerHide answer
Answer: C
R first gives Q=9 and P=2, but the routine processes Q next and sets T=9 + 2 = 11. P later lowers Q to 3, and Q’s outgoing edge is never revisited, leaving the reported 11. The true route R→P→Q→T weighs 2+1+2=5; assuming that answer was propagated silently repairs the invalid processing order.

Question 10 of 10

A takes 2 days. B takes 7 after A; C takes 5 after A; D takes 3 after both B and C. Unlimited parallel work is available. If B is shortened by 3 days and C is lengthened by 1, how does project completion change?
  1. It moves from day 12 to day 11.
  2. It moves from day 12 to day 9.
  3. It moves from day 12 to day 10.
  4. It stays at day 12 after the changes.
Show answerHide answer
Answer: A
Originally B finishes at day 9, C at day 7, and D at day 12. After the changes, B’s duration is 4 and C’s is 6, so their finishes become days 6 and 8; D then finishes at day 11. Moving completion to day 9 would subtract the entire 3-day saving on B while ignoring that C becomes the controlling branch.
Set 2: Read weighted routes and improve estimates10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

The only edges are R→P (2) and Q→P (3). What is the distance from R to Q?
  1. 0
  2. ∞
  3. 3
  4. 5
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

The parent records are p(T)=Q, p(Q)=P, and p(P)=R, with source R. What route do they describe?
  1. T→Q→P→R
  2. R→P→Q→T
  3. R→Q→P→T
  4. R→P→T→Q
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A route uses edges weighing 7, 0, and 4 minutes. What is its total travel time?
  1. 3 minutes
  2. 7 minutes
  3. 11 minutes
  4. 28 minutes
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A matrix uses 0 for every missing edge. The network also contains free connections. What representation change preserves those connections?
  1. Use ∞ for missing edges and 0 for free edges.
  2. Use 0 for missing edges and delete free edges.
  3. Use 1 for all free edges and 0 for missing edges.
  4. Use ∞ for free edges and 0 for missing edges.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A directed graph has R→P (13), R→Q (4), and Q→P (5). Why can BFS choose a heavier route from R to P?
  1. The one-edge route weighs 13; the two-edge route weighs 5.
  2. The one-edge route weighs 1; the two-edge route weighs 2.
  3. The one-edge route weighs 9; the two-edge route weighs 13.
  4. The one-edge route weighs 13; the two-edge route weighs 9.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Two different routes from R to T both weigh 9, and no route weighs less. What must two correct searches agree on?
  1. The full route, even if their distance values differ.
  2. The fewest-hop route, even if its weight is greater.
  3. The same parent tree, regardless of the tie-breaking rule.
  4. The distance 9, even if their parent choices differ.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

At one relaxation check, d(P)=8, w(P,Q)=−3, and d(Q)=7. What happens?
  1. Set d(Q)=5 and p(Q)=P.
  2. Set d(Q)=7 and p(Q)=P.
  3. Set d(Q)=11 and p(Q)=P.
  4. Keep d(Q)=7 and its old parent.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Relaxing P→Q offers a candidate weight of 12 when Q already has estimate 10. What update should a strict-improvement implementation make?
  1. Set Q’s estimate to 12 and its parent to P.
  2. Keep Q’s estimate at 10 but set its parent to P.
  3. Keep both Q’s estimate and its parent unchanged.
  4. Set Q’s estimate to 2 but keep its old parent.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A relaxation finds a route of weight 16 to Q. Why can this finite estimate be too high but not below Q’s true minimum?
  1. It is the first route found, so the minimum is exactly 16.
  2. It is an actual route weight, so the minimum is at most 16.
  3. It is an edge weight, so no multi-edge route can beat it.
  4. It is a route weight, so the minimum must be at least 16.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

The only edges are R→A (2), A→B (1), B→C (−5), C→B (2), C→T (4), R→D (7), and D→T (1). From R, which vertices have distance −∞?
  1. B, C, and T
  2. A, B, C, and T
  3. B and C only
  4. R, A, B, C, D, and T
Show answerHide answer

Save this lesson to see this answer.

Set 3: Inspect heap entries and Bellman–Ford rounds10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A lazy heap pops (17, P) while the stored estimate for P is 12. What should happen before scanning P’s edges?
  1. Reset P’s estimate to 17.
  2. Scan P’s edges using 17.
  3. Mark P unreachable.
  4. Skip this stale entry.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A graph may contain directed cycles and negative edges. Which algorithm provides source distances or detects a reachable negative cycle?
  1. Ordinary BFS
  2. Bellman–Ford
  3. Finish-once Dijkstra
  4. Topological DAG relaxation
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

For a graph without parallel edges, lazy deletion may keep O(E) heap entries. Why is its logarithmic heap factor still O(log⁡V)?
  1. E≤V2, so log⁡E≤2log⁡V.
  2. E ≤ V, so log E ≤ log V.
  3. E = V², so every heap has V entries.
  4. E ≥ V², so log E ≤ log V.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Edges are R→P (4), R→Q (9), and Q→P (−8). What distance to P is missed by a finish-once Dijkstra run?
  1. 1
  2. 4
  3. 9
  4. −4
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Bellman–Ford starts at R and scans Q→T (5), P→Q (−2), R→P (6) in that order. What are d(P), d(Q), and d(T) after round 2?
  1. 6, 4, 9
  2. 6, ∞, ∞
  3. 6, 4, ∞
  4. 6, −2, 3
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A Bellman–Ford run makes no changes during its second complete round. What can be concluded about later rounds from the same source?
  1. They still change parents on ties.
  2. They cannot improve any estimate.
  3. They can improve a vertex next round.
  4. They will find a negative cycle.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

The source reaches a negative cycle on P and Q. Q can reach T. There is no route from that cycle to R or U, although R is the source and R→U (8) exists. Which distances are −∞?
  1. P and Q only
  2. R, P, Q, and T
  3. P, Q, and T
  4. P, Q, T, and U
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A lazy-heap Dijkstra run starts at R on edges R→P (9), R→Q (2), Q→P (3), P→T (8), and Q→T (20). It stops when T is finished. How many stale entries are popped before that stop?
  1. 0
  2. 2
  3. 3
  4. 1
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Starting at R, Bellman–Ford scans P→Q (−4), Q→P (1), Q→T (2), R→P (7), R→U (5) in that order. With vertices R,P,Q,T,U, what does the extra round after four full rounds establish?
  1. A reachable negative cycle affects P, Q, and T.
  2. No cycle exists because R has no incoming edge.
  3. A negative edge makes every vertex’s distance −∞.
  4. T alone has −∞ because it is the last route vertex.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Rates are X→Y 0.8, Y→Z 1.25, and Z→X 1.04. What loop gain and transformed-weight sign follow?
  1. 4% gain; positive transformed sum.
  2. 4% gain; negative transformed sum.
  3. 0% gain; zero transformed sum.
  4. 20% loss; positive transformed sum.
Show answerHide answer

Save this lesson to see this answer.

Set 4: Compute distance tables and model directed trips10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

Before allowing Q as an intermediate vertex, d(P,T)=14, d(P,Q)=5, and d(Q,T)=6. What does this Floyd–Warshall update set d(P,T) to?
  1. 11
  2. 14
  3. 6
  4. 19
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What is the required outermost Floyd–Warshall loop variable when k names the allowed intermediate?
  1. i
  2. j
  3. k
  4. Either i or j
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Johnson’s potentials are h(P)=−5 and h(Q)=−2. What is the reweighted cost of an edge P→Q with original weight 4?
  1. 7
  2. 1
  3. −3
  4. 11
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

On a one-way road map, an app needs travel times from all intersections to depot D. What single-search construction answers that query?
  1. Keep edges and run Dijkstra from D.
  2. Reverse edges and run BFS from D.
  3. Keep edges and start Dijkstra at every intersection with 0.
  4. Reverse edges and run Dijkstra from D.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A route A takes 18 minutes and charges 2 money units. Route B takes 12 minutes and charges 5. The score is minutes plus 3 times the fee. Which route has the smaller score?
  1. Route B, with score 27.
  2. Route A, with score 20.
  3. Route A, with score 24.
  4. Route B, with score 17.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

All-pairs distances are needed in a dense directed graph with negative edges but no negative cycle. Compare Floyd–Warshall with repeating Bellman–Ford. What are their standard time bounds?
  1. O(V3) versus O(V4).
  2. O(V2) versus O(V3).
  3. O(V3) versus O(V2).
  4. O(V4) versus O(V3).
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

The only edges are 1→2 (3), 1→3 (11), 2→3 (4), and 3→1 (2). What are the final Floyd–Warshall distance rows, ordered 1,2,3?
  1. (0,3,11); (6,0,4); (2,5,0)
  2. (0,3,7); (6,0,4); (2,5,0)
  3. (0,3,7); (2,0,4); (2,5,0)
  4. (0,3,7); (6,0,4); (2,3,0)
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Edges are R→P (6), R→Q (8), Q→P (−5), and P→T (2). Johnson’s super-source potentials are h(R)=h(Q)=0, h(P)=−5, and h(T)=−3. What reweighted distance from R to T and recovered original distance result?
  1. Reweighted 8; original 5.
  2. Reweighted 5; original 5.
  3. Reweighted 8; original 11.
  4. Reweighted 11; original 8.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A map has U→P (4), P→Station A (7), U→Q (6), Q→Station B (2), and Station A→U (1). What is U’s time toward its nearest station, and what would an unchanged-graph multi-source run report at U?
  1. Toward station 1; unchanged-graph result 8.
  2. Toward station 11; unchanged-graph result 1.
  3. Toward station 8; unchanged-graph result 11.
  4. Toward station 8; unchanged-graph result 1.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

The only roads are R→P (3), P→T (4), R→Q (5), and Q→T (4). Passing through P costs 4 extra minutes and passing through Q costs 1. Endpoints have no extra cost. What is the minimum R-to-T time when these costs are modeled?
  1. 7 minutes through P.
  2. 9 minutes through Q.
  3. 10 minutes through Q.
  4. 11 minutes through P.
Show answerHide answer

Save this lesson to see this answer.

Set 5: Combine algorithm choice, traces, and model checks10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

If d(P)=∞, what finite improvement can relaxing P→Q (−6) provide?
  1. It sets Q to −6.
  2. None while P remains unreachable.
  3. It sets Q to 0.
  4. It sets P to −6.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A directed graph has nonnegative weights, no parallel edges, and E proportional to V². What time bounds do array-based and binary-heap Dijkstra have?
  1. Array O(V2); binary heap O(V2log⁡V).
  2. Array O(V3); binary heap O(V2log⁡V).
  3. Array O(V2); binary heap O(Vlog⁡V).
  4. Array O(Vlog⁡V); binary heap O(V2).
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A negative cycle lies in a component unreachable from source R. How should a test be changed to detect any negative cycle in the whole graph?
  1. Add a zero edge from every vertex into R.
  2. Run Dijkstra from R with all weights unchanged.
  3. Add a zero-edge super-source linked to every vertex.
  4. Perform twice as many rounds from R alone.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A graph with no negative cycles is reweighted by Johnson’s potentials. A corrected P-to-Q distance is 12, h(P)=−4, and h(Q)=−1. What is the original distance?
  1. 9
  2. 7
  3. 12
  4. 15
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Edges are R→P (6), R→Q (10), Q→P (−7), and P→T (2). A programmer adds 7 to every edge and runs Dijkstra. Which R-to-T route wins before and after the shift?
  1. Before R→Q→P→T; after R→P→T.
  2. Before R→P→T; after R→Q→P→T.
  3. Before R→Q→P→T; after R→Q→P→T.
  4. Before R→P→T; after R→P→T.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A graph has vertices R,P,Q,T and edge order Q→T (1), P→Q (−2), R→P (5), R→T (12). A routine reports after two Bellman–Ford rounds that T’s distance is 12. Is that final, and what should it become?
  1. Final; all four vertices were discovered by round 2.
  2. Not final; the third round gives 3.
  3. Not final; the third round gives 4.
  4. Not final; the third round gives −∞.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An all-pairs matrix calculation ends with d(Q,Q)<0. Original edges are R→P (2), P→Q (3), Q→Q (−1), Q→T (4), and U→T (1). Which ordered pairs have distance −∞?
  1. Starts R,P,Q,U and ends Q,T.
  2. Starts R,P,Q and ends Q,T.
  3. Starts R,P,Q and ends P,Q,T.
  4. Starts Q only and ends Q,T.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A sparse directed road graph has nonnegative times and E proportional to V. For every intersection, a service needs the time toward the nearest of 30 depots. What construction answers this with one binary-heap search, and what is its time bound?
  1. Keep edges; start depots at 0; O(Vlog⁡V).
  2. Reverse edges; search from every vertex; O(V2log⁡V).
  3. Keep edges; search from every depot; O(Vlog⁡V).
  4. Reverse edges; start depots at 0; O(Vlog⁡V).
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A takes 3 days. B takes 4 after A; C takes 6 after A; D takes 2 after B; E takes 1 after C and D. With unlimited parallel jobs, how much later does the project finish if B alone takes 6 days?
  1. No later.
  2. 1 day later.
  3. 2 days later.
  4. 3 days later.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

After a Bellman–Ford check round on six vertices, an improved T has parents p(T)=C, p(C)=B, p(B)=A, p(A)=B, with source R and an isolated U. The cycle edges are A→B (2) and B→A (−5). What witness is recovered, and which listed downstream vertices share its −∞ value?
  1. T→C→B→A; also R and U.
  2. B→A→B; also C and T.
  3. B→A→B; also R and U.
  4. A→B→C→T; also A and B.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

55 Key Terms, each with its definition

A

Additive objective
An additive objective scores a route by summing its edge contributions in one consistent quantity or explicitly defined combined score.
Travel minutes plus a fee times a minutes-per-money factor gives a chosen time-and-cost route score.
Adjacency list
An adjacency list stores each vertex’s outgoing neighbors beside their edge weights, using space proportional to vertices plus edges.
A vertex with two outgoing edges can store the pairs (P, 6) and (Q, 2) in its neighbor list.
Adjacency matrix
An adjacency matrix is a square table whose row and column identify an ordered vertex pair and whose entry stores its direct edge weight.
The entry ∞ can mark a missing edge, leaving 0 available to represent a real connection with no cost.
All-pairs shortest paths
All-pairs shortest paths computes the minimum route weight for every ordered pair of graph vertices, usually as a square distance matrix.
Repeated single-source searches fill one row per start vertex until the full table has been computed.
Arbitrage
Arbitrage is a loop of currency trades whose exchange-rate product exceeds one, so the loop returns more of the starting currency.
A loop product of 1.06 turns 100 units into 106 units before another lap around the trades.

B

Bellman–Ford algorithm
The Bellman–Ford algorithm repeatedly relaxes every edge to find source distances with negative weights and checks for a reachable negative cycle.
A reversed edge order can require three rounds to propagate a route containing three successive edges.

C

Check round
A check round scans the edges once after Bellman–Ford’s V−1 rounds and tests for further improvements that reveal a source-reachable negative cycle.
An edge that still lowers Q in the extra scan prevents reporting all current numbers as final distances.
Constant edge shift
A constant edge shift adds the same number to every edge weight, changing a path’s total by that number times its edge count.
Adding 5 to each edge penalizes a three-edge route by 15 but penalizes a direct route by only 5.
Critical path
A critical path is a longest chain of dependent jobs whose total duration determines earliest project completion when parallel work is unrestricted.
A delay to a job on a critical chain delays completion because that chain already uses the full project time.

D

DAG relaxation
DAG relaxation finds shortest paths by processing vertices in topological order and relaxing each outgoing edge once, allowing any edge weights.
A negative edge from an earlier vertex can improve a later vertex without forcing an additional pass.
Decrease-key
Decrease-key lowers the priority of an existing queue item after a better candidate is found, allowing an indexed heap to keep one item per vertex.
An improved route from cost 11 to cost 6 lowers the queued vertex’s key without inserting a second copy.
Dense graph
A dense graph has an edge count close to the number of possible vertex pairs, so scanning a full array can compete well with heap operations.
For E proportional to V², array-based Dijkstra has an O(V2) bound instead of a binary heap’s extra logarithm.
Dijkstra’s algorithm
Dijkstra’s algorithm finds shortest paths with nonnegative weights by repeatedly finishing the smallest unfinished source-distance estimate.
A tentative estimate of 12 can fall to 7 while its vertex waits for removal from the priority queue.
Directed acyclic graph
A directed acyclic graph is a directed graph with no directed cycle, so its vertices can be arranged with every edge pointing forward.
A chain of prerequisites cannot form a DAG if one task indirectly requires itself to finish first.
Distance estimate
A distance estimate is the best source-route weight currently recorded for a vertex, initially infinite except at the source.
An estimate of 15 may later fall to 9 when a newly reached predecessor offers a lighter route.
Dynamic program
A dynamic program computes results from previously solved dependent results, with a base case and an evaluation order that respects those dependencies.
In a DAG, the distance to Q is computed after the incoming predecessor distances are available.

E

Earliest finish
A job’s earliest finish is its duration plus the latest earliest finish among its prerequisites, using zero when it has no prerequisites.
A 3-day job whose prerequisites finish on days 5 and 8 can finish no earlier than day 11.
Early stopping
Early stopping ends Bellman–Ford’s remaining rounds when a complete round makes no improvement, because the estimates can no longer change.
If round 2 changes nothing, performing the same edge scan in round 3 cannot uncover a new candidate.

F

Finished vertex
A finished vertex is one whose estimate has been selected as the unfinished minimum and certified as its final distance by Dijkstra’s argument.
Discovering T at cost 9 does not finish it if a later relaxation can offer a route of cost 6.
Floyd–Warshall algorithm
The Floyd–Warshall algorithm updates every vertex pair while progressively allowing additional intermediate vertices, using cubic time and quadratic space.
Allowing Q as a stop improves P→T when the known P→Q and Q→T routes beat the current entry.
Frontier
The frontier is the collection of discovered but unfinished vertices whose tentative source distances are candidates for the next search step.
The next chosen vertex may be elsewhere in the frontier, even when the current vertex has an outgoing edge.

G

Greedy choice
A greedy choice commits to the best current candidate using a property that makes the local decision safe for the complete solution.
Dijkstra commits to the smallest unfinished estimate because continuing over nonnegative edges cannot lower it.

I

Infinity sentinel
An infinity sentinel is a value used to mark an unreachable estimate, which must not be confused with a genuine finite route weight.
Before adding an edge cost to a maximum-integer sentinel, skip the unreachable starting vertex.
Intermediate vertex
An intermediate vertex is an internal stop on a path, distinct from its endpoints, whose permission to appear defines a Floyd–Warshall stage.
At stage k, routes may use any of the first k numbered vertices internally, not just vertex k.

J

Johnson’s algorithm
Johnson’s algorithm obtains vertex potentials with Bellman–Ford, reweights edges to nonnegative values, and runs Dijkstra from every vertex.
A sparse graph with negative edges and no negative cycle can use reweighting to avoid repeated Bellman–Ford runs.

L

Layered distance
A layered distance records the best route using at most a specified number of edges, giving Bellman–Ford a dynamic-programming interpretation.
The layer for at most two edges extends only values from the layer for at most one edge.
Lazy deletion
Lazy deletion handles improved priorities by inserting fresh entries and postponing removal of outdated entries until they reach the top of the heap.
A distance-6 entry is processed before the older distance-11 entry for the same vertex is discarded.
Log-transformed rate
A log-transformed rate assigns an exchange edge the negative logarithm of its rate, converting profitable rate products into negative path sums.
A trade-loop product above 1 has a positive logarithm and therefore a negative transformed total.
Longest path in a DAG
A longest path in a DAG has maximum total edge weight among routes with the same endpoints and can be found by maximum updates in topological order.
Negating a DAG’s weights lets shortest-path relaxation recover its maximum original route weight.

M

Min-priority queue
A min-priority queue stores items with numerical priorities and removes an item with the smallest priority when asked for the next item.
A search uses source-distance estimates as priorities so the next removal offers the nearest unfinished vertex.
Multi-source search
A multi-source search initializes several start vertices at distance zero and finds the minimum route weight from any of those starts.
On a reversed map, stations started at zero give each intersection its travel time to the nearest station.

N

Negative cycle
A negative cycle is a directed loop whose edge weights sum to less than zero, so each additional lap lowers a route’s cost.
A loop with weights 4, −7, and 1 reduces the total by 2 every time a route goes around it.
Negative edge
A negative edge has a weight below zero and can lower the cost of a route that reaches it, even when no directed cycle exists.
A route reaching Q at 8 and then taking Q→P at −7 arrives at P with total weight 1.
Negative-cycle witness
A negative-cycle witness is an explicit directed loop with negative total weight that demonstrates why affected shortest distances are unbounded below.
Following parents into a loop and reversing the collected order yields a route whose weights can be summed.

O

Optimal substructure
Optimal substructure means that every segment of a shortest path is itself a shortest path between the segment’s endpoints.
Replacing a route segment with a lighter connection would also lower the cost of the whole route.

P

Parent pointer
A parent pointer records the vertex immediately before another vertex on the best source route currently chosen by the algorithm.
If the parent of T is P, reconstructing the route to T first moves backward from T to P.
Potential
A potential is a vertex value obtained from super-source distances that makes the corrected edge weight nonnegative in Johnson’s algorithm.
Potentials h(P)=−2 and h(Q)=0 turn a weight-3 edge P→Q into a corrected weight of 1.
Precedence constraint
A precedence constraint requires one job to finish before another job can start, creating a directed dependency in a project schedule.
Testing that requires both Build and Review must wait until the later of those two jobs finishes.

R

Relaxation
Relaxation checks whether extending the current route to an edge’s start improves its end, and updates the distance and parent if it does.
With d(P)=4 and P→Q weighted 3, an existing estimate of 9 for Q improves to 7.
Relaxation round
A relaxation round is one complete scan of all graph edges, with each edge given a chance to improve its destination’s distance estimate.
An unchanged edge near the start of a round does not justify skipping the remaining edges in that scan.
Reprocessing
Reprocessing means scanning a vertex’s outgoing edges again after its estimate improves, which loses Dijkstra’s finish-once bound with negative edges.
A later negative edge can trigger another scan of an earlier vertex and then more scans of its descendants.
Reversed graph
A reversed graph replaces every directed edge with an edge of the same weight in the opposite direction, preserving routes with their endpoints swapped.
A search outward from a hospital in the reversed map measures original trips toward that hospital.

S

Shortest-path distance
A shortest-path distance is the minimum total edge weight from a chosen start to a destination, with special values for unreachable or unbounded cases.
A distance of 6 can belong to a three-edge route even when a direct edge to the same destination weighs 10.
Shortest-path tree
A shortest-path tree is a set of source-rooted parent edges that provides one shortest route to every reachable vertex with finite distance.
Two equally light routes to Q can lead two searches to choose different parent edges in their trees.
Simple path
A simple path is a path that repeats no vertex and therefore uses at most one fewer edge than the graph has vertices.
In a five-vertex graph, a simple path can use four edges but cannot include a return to its starting vertex.
Slack
Slack is the amount a job can be delayed from its earliest timing without postponing the earliest completion time of the whole project.
A review finishing on day 6 can have 2 days of slack if its dependent job only needs it by day 8.
Sparse graph
A sparse graph has relatively few edges compared with the number of possible vertex pairs, making adjacency lists a useful storage choice.
With only a few outgoing links per vertex, storing all possible pairs would leave many unused matrix entries.
Stale entry
A stale entry is an old queued distance that exceeds its vertex’s current estimate and should be skipped before scanning outgoing edges.
Popping (14, P) when P already has estimate 8 signals that this heap record is obsolete.
Super-source
A super-source is an added vertex with zero-weight outgoing edges to several chosen vertices, letting one search start from all of them.
Connecting it to every vertex lets Bellman–Ford detect a negative cycle in any disconnected component.

T

Telescoping sum
A telescoping sum cancels adjacent opposite terms, leaving an endpoint correction when Johnson’s potentials are added along a path.
In a path S→P→T, the added −h(P) and +h(P) cancel, leaving only h(S)−h(T).
Topological order
A topological order lists a DAG’s vertices so that the starting vertex of every directed edge appears before its destination.
For P→Q and Q→T, an order beginning T, P, Q is invalid because it puts a dependency after T.
Triangle inequality
The shortest-path triangle inequality states that a best distance to a vertex is no greater than a route reaching it through an incoming edge.
A candidate of 8 through P shows that the true shortest distance to Q cannot be greater than 8.

V

Vertex splitting
Vertex splitting replaces a location with arrival and departure copies joined by an edge that carries a cost charged at that location.
A 4-minute transfer becomes an internal edge that every route making that transfer must cross.

W

Weight function
A weight function maps every graph edge to the number that measures its contribution to a route’s additive objective.
For a network-delay graph, the weight of one link might be 7 milliseconds and another 12 milliseconds.
Weighted graph
A weighted graph assigns a numerical cost to each edge, so a route can be evaluated by adding the costs of its edges.
A road graph can attach minutes of travel time to each directed segment between two intersections.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started