- Learn
- Computer Science & IT
- Programming
- Data Structures and Algorithms
- Shortest Path Algorithms
Shortest Path Algorithms in Weighted Graphs
IntermediateLesson 9 of 10 in Data Structures and Algorithms Course
What you will learn
- 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 enoughStore 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 treesState 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 estimatesKeep a distance estimate for every vertex, lower it with the relaxation step, and use the triangle inequality to tell when the estimates are exact.
- Represent weighted graphs and see why BFS is not enough
- 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 orderProcess 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 DAGTurn 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.
- Run DAG relaxation in topological order
- 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 stepRun 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 itCode 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 algorithmUse a small counterexample to show how a negative edge leads Dijkstra's algorithm to a wrong distance, and choose a correct algorithm instead.
- Trace Dijkstra's algorithm step by step
- 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 relaxationRelax every edge in V−1 rounds, explain why that many rounds are enough, and trace and analyze the algorithm.
- Detect, find and use negative cyclesUse 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.
- Run Bellman–Ford in rounds of relaxation
- 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 pathsCompare 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 problemsPick the right shortest-path algorithm from the graph and its weights, and turn route-planning questions on road maps into weighted graphs.
- Compute all-pairs shortest paths
Shortest Path Algorithms study guide
1Model 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 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.
| Representation | Space | Useful operation |
|---|---|---|
| Adjacency list | Scan the edges leaving a vertex | |
| Adjacency matrix | 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: .
- S→A→C→T: .
- S→B→C→T: .
The route S→B→A→C→D→T has five edges, yet weighs only . 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 space; matrices use .
- 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 .
| Situation | Distance from s to t |
|---|---|
| A minimum-weight route exists | Its 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 . 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:
| Vertex | Distance | Parent |
|---|---|---|
| B | 2 | S |
| A | 3 | B |
| C | 8 | A |
| D | 10 | C |
| T | 12 | D |
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:
If , replace the estimate and its parent together:
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 . 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:
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:
The best route to v cannot be heavier than a particular route through u. An edge with 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 , 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.
2Find 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 processed | Improvements made |
|---|---|
| A | B becomes 3; C becomes 6 |
| B | C becomes 1; D becomes 7 |
| C | D becomes 2; E becomes 6 |
| D | E becomes −1 |
| E | No outgoing edges |
For example, processing B uses to improve C. Processing D later uses 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 . For any other vertex, take the minimum of 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 time. The distance pass visits V vertices and relaxes E edges once, so the total stays . 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 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:
Use 0 when a job has no prerequisites. Consider this project:
| Job | Duration | Prerequisites | Earliest finish |
|---|---|---|---|
| Design | 3 days | None | 3 |
| Backend | 5 days | Design | 8 |
| Frontend | 4 days | Design | 7 |
| Docs | 1 day | Design | 4 |
| Testing | 2 days | Backend, Frontend | 10 |
| Release | 1 day | Testing, Docs | 11 |
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 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 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.
3Compute 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.
| Finish | Distance | Updates to unfinished vertices |
|---|---|---|
| S | 0 | A=4, B=2 |
| B | 2 | A=3, C=10, D=12 |
| A | 3 | C=8 |
| C | 8 | D=10, T=14 |
| D | 10 | T=12 |
| T | 12 | None |
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 .
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 entries and uses extra space including distances and parents.
For graphs without parallel edges, , so . Including initialization and heap work gives time. When all vertices are reachable, it is often written .
| Queue choice | Total time | Main tradeoff |
|---|---|---|
| Array scan | Useful on dense graphs | |
| Binary heap | Practical on sparse graphs | |
| Fibonacci heap | 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 entries.
- Binary-heap Dijkstra takes 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 . 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 . 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 . 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:
| Input | Correct single-source choice |
|---|---|
| DAG, including negative edges | Topological relaxation |
| General graph, all weights at least 0 | Dijkstra's algorithm |
| General graph with negative edges | Bellman–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.
4Handle 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 round | S | A | B | C |
|---|---|---|---|---|
| Initialization | 0 | ∞ | ∞ | ∞ |
| 1 | 0 | 4 | 5 | ∞ |
| 2 | 0 | 3 | 5 | 7 |
| 3 | 0 | 3 | 5 | 6 |
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 . Round 3 propagates that improvement to C, giving .
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 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:
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: time, plus initialization, and extra space for estimates and parents. A queue of changed vertices can reduce practical work but retains the 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 time and 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 .
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 , an 8% gain.
Assign each trade the weight . Logarithms turn multiplication into addition, and the minus sign turns profitable products into negative sums:
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 turn profitable exchange loops into negative cycles.
5Compute 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 entries.
Repeat a single-source method
Running from each vertex gives these bounds:
| Input | Repeated method | Total time |
|---|---|---|
| DAG | DAG relaxation | |
| Nonnegative weights | Binary-heap Dijkstra | |
| General weights | Bellman–Ford |
The last bound becomes 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 be the lightest route whose intermediate vertices come from 1 through k. A best route either avoids k or passes through k:
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 time and 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 or detects a negative cycle. Reweight every edge:
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 . Run Dijkstra from every vertex, then recover original distances with .
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 with a binary heap, or 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 entries.
- Floyd–Warshall allows one more intermediate vertex in each outer iteration.
- Keep k outermost for time and 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 .
- 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 weights | Single-source method | Time |
|---|---|---|
| Unweighted or equal positive weights | BFS | |
| DAG with any weights | Topological relaxation | |
| General graph, nonnegative weights | Binary-heap Dijkstra | |
| General graph with negative weights | Bellman–Ford and cycle check |
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
1From road costs to distance estimates
14 steps
- 1IntroductionGive 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.
- 2ExplanationStore 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. - 3ExampleCompare 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 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.
- 4ChallengeChoose 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.
- 5ExplanationRead a distance value
The distance 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.
- 6ExampleCheck 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.
- 7Key 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.
- 8ChallengeTurn 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.
- 9ExplanationInitialize what is actually known
Set 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.
- 10ExampleOffer a new route through an edge
Suppose , the edge L→M weighs 4, and . Reaching L and continuing to M offers the candidate .
Because 9 is smaller than 12, set and . These two changes belong together: the number records the improved weight, and the parent records the last step of the route that produced it.
- 11ChallengeDecide whether to change a record
Now , L→M weighs 4, and . 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.
- 12TipDo 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. - 13ChallengeDiagnose a premature answer
An edge scan begins with 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 , 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.
- 14RecapConnect 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.
2Solve routes and schedules in a DAG
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionLet the dependencies choose the order
- 2ExplanationPut predecessors first
- 3ExampleStart the DAG trace
- 4ExampleCarry the improvement forward
- 5ChallengeTest an unsafe processing order
- 6Key InsightCount each dependency once
- 7ConnectionChange minimum into maximum
- 8ExampleRead a parallel project
- 9ExampleWait for the latest prerequisite
- 10ChallengeFind the available slack
- 11ExplanationMove a job duration onto an edge
- 12ChallengeExplain the scheduling choice
- 13RecapReuse the order, choose the right comparison
3Trace and implement Dijkstra safely
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionCommit only when a distance is ready
- 2ExplanationChoose the smallest unfinished total
- 3ExampleDiscover the first candidates
- 4ChallengeChoose the next unfinished vertex
- 5ExampleFinish the target
- 6Key InsightFind where nonnegative weights matter
- 7ExplanationLeave old heap entries for later
- 8ExampleSpot a stale pop in the trace
- 9ChallengePlace the target test correctly
- 10TipHandle ties and count heap work
- 11ExampleA negative edge arrives too late
- 12ChallengeCheck the constant-shift repair
- 13ExplanationRevisiting loses the finish-once guarantee
- 14ChallengeChoose for a changing graph
- 15RecapCheck the guarantee before trusting the heap
4Use Bellman–Ford to find distances or a negative cycle
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionKeep a route open to later improvement
- 2ExplanationSet the round budget
- 3ExampleRound 1 discovers the starting branches
- 4ExampleRound 2 improves an earlier route
- 5ChallengeComplete the third round
- 6Key InsightSeparate in-place rounds from layers
- 7TipStop after a whole quiet round
- 8ExplanationAsk whether any improvement remains
- 9ExampleAdd a loop that never settles
- 10ExplanationEnter the cycle before collecting it
- 11ChallengeMark only the affected destinations
- 12ConnectionDetect profit by adding logarithms
- 13ChallengeCheck an entire exchange graph
- 14RecapReport a finished answer in either case
5Build all-pairs answers and directed routing models
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionChoose what the output must answer
- 2ExplanationCount the distance table
- 3ExampleInitialize a Floyd–Warshall matrix
- 4ExampleAllow the first two intermediate vertices
- 5ChallengeFinish the matrix stages
- 6Key InsightInspect the diagonal before reporting distances
- 7ExplanationMake sparse negative-edge searches nonnegative
- 8ExampleCancel the interior potential terms
- 9ChallengeSelect an all-pairs strategy
- 10ExplanationLet the objective pick the weights
- 11ExampleSearch toward a destination
- 12ChallengeChoose the direction for nearest stations
- 13ExampleCharge a transfer exactly where it occurs
- 14TipUse the strongest input structure
- 15ChallengeCombine the model with the algorithm
- 16RecapCheck endpoints, weights, and output size
Shortest Path Algorithms practice questions
Set 1: Trace DAG routes and Dijkstra’s choices10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
Show answerHide answer
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Additive objective
Adjacency list
(P, 6) and (Q, 2) in its neighbor list.Adjacency matrix
All-pairs shortest paths
Arbitrage
B
Bellman–Ford algorithm
C
Check round
Constant edge shift
Critical path
D
DAG relaxation
Decrease-key
Dense graph
Dijkstra’s algorithm
Directed acyclic graph
Distance estimate
Dynamic program
E
Earliest finish
Early stopping
F
Finished vertex
Floyd–Warshall algorithm
Frontier
G
Greedy choice
I
Infinity sentinel
Intermediate vertex
J
Johnson’s algorithm
L
Layered distance
Lazy deletion
Log-transformed rate
Longest path in a DAG
M
Min-priority queue
Multi-source search
N
Negative cycle
Negative edge
Negative-cycle witness
O
Optimal substructure
P
Parent pointer
Potential
Precedence constraint
R
Relaxation
Relaxation round
Reprocessing
Reversed graph
S
Shortest-path distance
Shortest-path tree
Simple path
Slack
Sparse graph
Stale entry
(14, P) when P already has estimate 8 signals that this heap record is obsolete.Super-source
T
Telescoping sum
Topological order
Triangle inequality
V
Vertex splitting
W
Weight function
Weighted graph
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.