CoursifyCoursify

Shortest-Path Algorithms for a City Road Network

Shortest-Path Algorithms for a City Road Network

Verified Sources
May 27, 2026

A city road network can be modeled as a graph where vertices denote locations and edges denote roads. The design question is: given a source location, which algorithm should compute the shortest path under different road-length assumptions? The correct choice depends entirely on the edge-weight model.2

For the three cases in the prompt, the standard choices are:

Road modelRecommended algorithmWhy
All roads have equal lengthBreadth-First Search (BFS)Minimizes the number of edges traversed, which is equivalent to minimizing total distance when every edge has the same cost.2
Roads have varying lengths, but no negative lengthsDijkstra’s algorithmCorrect for nonnegative weights because once the smallest tentative distance is chosen, it never needs to be improved later.2
Some roads have negative lengthsBellman–Ford algorithmHandles negative edges by repeated relaxation and can detect negative cycles, where no finite shortest path exists.2

This is fundamentally a single-source shortest path decision problem. If one source location is fixed and we want distances to many other locations, these three algorithms form the canonical toolkit.2

A useful conceptual map is:

Footnotes

  1. Shortest Path Algorithm Comparison: Two Questions Decide - Concise comparison of BFS, Dijkstra, and Bellman-Ford by graph weight conditions and complexity. 2

  2. Bellman-Ford - finding shortest paths with negative weights - Detailed explanation of Bellman-Ford, repeated relaxation, and negative-cycle detection. 2

  3. Understanding connection between minimum spanning tree, shortest path, breadth first and depth first traversal - Summarizes the CLRS statement that BFS gives shortest-path distances in unweighted graphs.

  4. Dijkstra's algorithm - Wikipedia - Notes that BFS is a special case of Dijkstra on unweighted graphs.

  5. Dijkstra's algorithm - Wikipedia - Describes Dijkstra’s purpose, nonnegative-weight requirement, and standard complexity. 2

  6. Chapter 12 Shortest Paths (CMU lecture notes) - Explains why Dijkstra works for nonnegative edges and fails with negative ones.

  7. Bellman–Ford algorithm - Wikipedia - Describes Bellman-Ford’s O(VE)O(|V||E|) runtime, handling of negative weights, and negative-cycle detection.

Shortest Path Algorithms (Dijkstra and Bellman-Ford) - Simplified

Core Selection Rule

Choose the algorithm by inspecting edge weights first: equal weights \rightarrow BFS, nonnegative weights \rightarrow Dijkstra, negative weights \rightarrow Bellman-Ford.2

Footnotes

  1. Shortest Path Algorithm Comparison: Two Questions Decide - Concise comparison of BFS, Dijkstra, and Bellman-Ford by graph weight conditions and complexity.

  2. Bellman-Ford - finding shortest paths with negative weights - Detailed explanation of Bellman-Ford, repeated relaxation, and negative-cycle detection.

Case (i): All Roads Have Equal Length \rightarrow BFS

If every road has identical length, then the total path cost is proportional to the number of roads used. In that setting, minimizing distance is the same as minimizing the number of edges on the path. Breadth-First Search explores the graph level by level, so it discovers every vertex first through a path with the minimum number of edges.2

Why this works:

  • BFS visits all vertices at distance 11 edge from the source before any at distance 22.
  • Then it visits all vertices at distance 22 before any at distance 33.
  • Therefore, the first time a vertex is reached, BFS has found a shortest path in terms of edge count.

If every road length is exactly LL, then a path with kk edges has total length kLkL. Since LL is constant, minimizing kLkL is equivalent to minimizing kk:

cost(P)=kL\operatorname{cost}(P)=kL

So:

argminPcost(P)=argminPk\arg\min_P \operatorname{cost}(P)=\arg\min_P k

That is exactly what BFS optimizes.2

In practical city terms, if each road segment is treated as equally costly—perhaps in a coarse routing model where every block is approximated as one unit—BFS is both correct and efficient. Its time complexity is:

O(V+E)O(|V|+|E|)

where V|V| is the number of locations and E|E| is the number of roads.2

Footnotes

  1. Understanding connection between minimum spanning tree, shortest path, breadth first and depth first traversal - Summarizes the CLRS statement that BFS gives shortest-path distances in unweighted graphs. 2 3 4 5

  2. Dijkstra's algorithm - Wikipedia - Notes that BFS is a special case of Dijkstra on unweighted graphs. 2

  3. Shortest Path Algorithm Comparison: Two Questions Decide - Concise comparison of BFS, Dijkstra, and Bellman-Ford by graph weight conditions and complexity.

How BFS Finds Shortest Paths When All Roads Are Equal

  1. 1
    Step 1

    Set the source location distance to 00, mark all other distances as infinity, and place the source in a FIFO queue.

    Footnotes

    1. Understanding connection between minimum spanning tree, shortest path, breadth first and depth first traversal - Summarizes the CLRS statement that BFS gives shortest-path distances in unweighted graphs.

  2. 2
    Step 2

    Remove the front location from the queue and inspect all adjacent roads. Any undiscovered neighbor is assigned distance equal to the current distance plus 11 and is added to the queue.2

    Footnotes

    1. Understanding connection between minimum spanning tree, shortest path, breadth first and depth first traversal - Summarizes the CLRS statement that BFS gives shortest-path distances in unweighted graphs.

    2. Dijkstra's algorithm - Wikipedia - Notes that BFS is a special case of Dijkstra on unweighted graphs.

  3. 3
    Step 3

    Store the previous location for each newly discovered node so that an actual route can be reconstructed after traversal.

  4. 4
    Step 4

    Because nodes are processed in increasing edge-distance order, the first recorded distance for each reachable location is optimal.

    Footnotes

    1. Understanding connection between minimum spanning tree, shortest path, breadth first and depth first traversal - Summarizes the CLRS statement that BFS gives shortest-path distances in unweighted graphs.

  5. 5
    Step 5

    Follow predecessor pointers backward from the destination to the source to recover the shortest route.

BFS Is a Special Case of Weighted Shortest Paths

When all edge weights are identical, weighted shortest paths collapse to minimum-edge paths, so BFS is sufficient and faster than heavier weighted algorithms.2

Footnotes

  1. Dijkstra's algorithm - Wikipedia - Notes that BFS is a special case of Dijkstra on unweighted graphs.

  2. Dijkstra's algorithm - Wikipedia - Describes Dijkstra’s purpose, nonnegative-weight requirement, and standard complexity.

Case (ii): Roads Have Varying Lengths but No Negative Lengths \rightarrow Dijkstra’s Algorithm

When road lengths vary, minimizing the number of roads is no longer enough. A route with fewer roads may still be longer in total distance than a route with more roads. We therefore need an algorithm that minimizes the sum of edge weights.

Dijkstra’s algorithm is the standard choice when all road lengths are nonnegative. It maintains a priority queue of tentative distances and repeatedly finalizes the not-yet-processed location with smallest known distance.2

The key correctness condition is nonnegativity. Suppose the algorithm extracts a location uu with smallest tentative distance. If every edge weight is at least 00, then any alternative path reaching uu later through unexplored vertices cannot be shorter, because extending a path cannot reduce its total cost.2 This greedy argument fails if negative edges exist.

Formally, if path cost is the sum of edge lengths,

dist(v)=minP:svePw(e)\operatorname{dist}(v)=\min_{P:s\leadsto v}\sum_{e\in P} w(e)

then Dijkstra computes these values correctly when

w(e)0for all edges ew(e)\ge 0 \quad \text{for all edges } e

Its runtime depends on implementation. With a binary heap priority queue, the standard complexity is approximately

O((V+E)logV)O((|V|+|E|)\log |V|)

or equivalently O(ElogV)O(|E|\log |V|) on sparse graphs.3

This makes Dijkstra highly suitable for realistic road networks, since actual road distances and travel times are usually nonnegative.

Footnotes

  1. Dijkstra's algorithm - Wikipedia - Describes Dijkstra’s purpose, nonnegative-weight requirement, and standard complexity. 2 3 4 5

  2. Chapter 12 Shortest Paths (CMU lecture notes) - Explains why Dijkstra works for nonnegative edges and fails with negative ones. 2 3

  3. Shortest Path Algorithm Comparison: Two Questions Decide - Concise comparison of BFS, Dijkstra, and Bellman-Ford by graph weight conditions and complexity.

How Dijkstra’s Algorithm Works for Nonnegative Road Lengths

  1. 1
    Step 1

    Set the source distance to 00, all others to infinity, and insert the source into a min-priority queue.

    Footnotes

    1. Dijkstra's algorithm - Wikipedia - Describes Dijkstra’s purpose, nonnegative-weight requirement, and standard complexity.

  2. 2
    Step 2

    Remove the location with smallest tentative distance from the queue. Its shortest-path value is now finalized under the nonnegative-weight assumption.2

    Footnotes

    1. Dijkstra's algorithm - Wikipedia - Describes Dijkstra’s purpose, nonnegative-weight requirement, and standard complexity.

    2. Chapter 12 Shortest Paths (CMU lecture notes) - Explains why Dijkstra works for nonnegative edges and fails with negative ones.

  3. 3
    Step 3

    For each neighboring location, test whether going through the current node gives a shorter total path. If so, update the distance and predecessor, then update the priority queue.2

    Footnotes

    1. Bellman-Ford - finding shortest paths with negative weights - Detailed explanation of Bellman-Ford, repeated relaxation, and negative-cycle detection.

    2. Dijkstra's algorithm - Wikipedia - Describes Dijkstra’s purpose, nonnegative-weight requirement, and standard complexity.

  4. 4
    Step 4

    The algorithm continues selecting the nearest unsettled node and relaxing its outgoing edges until all reachable locations have final shortest distances.

  5. 5
    Step 5

    Use predecessor links to reconstruct the actual shortest route from source to destination.

Why Dijkstra Is Not Appropriate for Negative Roads

If a negative road exists, a path that looks longer initially may later become shorter after taking that negative edge. This breaks the greedy invariant used by Dijkstra.2

Example idea:

  • Suppose the current best path to bb is 22.
  • Another node aa has current distance 33.
  • There is an edge from aa to bb with weight 2-2.
  • Then going through aa yields total cost 11, better than 22.

A greedy algorithm that finalized bb too early would be wrong. Therefore, Dijkstra should not be used when negative edges are possible.3

In this graph, the direct tentative route to BB has cost 22, but the path SABS \rightarrow A \rightarrow B has cost 11. This is exactly the kind of situation that invalidates Dijkstra’s greedy choice.

Footnotes

  1. Bellman-Ford - finding shortest paths with negative weights - Detailed explanation of Bellman-Ford, repeated relaxation, and negative-cycle detection. 2

  2. Chapter 12 Shortest Paths (CMU lecture notes) - Explains why Dijkstra works for nonnegative edges and fails with negative ones. 2 3 4

  3. Dijkstra's algorithm - Wikipedia - Describes Dijkstra’s purpose, nonnegative-weight requirement, and standard complexity.

Case (iii): Some Roads Have Negative Lengths \rightarrow Bellman–Ford

If some edges are negative, the appropriate algorithm is Bellman–Ford.2 It does not greedily finalize vertices. Instead, it repeatedly relaxes all edges, gradually propagating improvements through the graph.

Its logic is based on the fact that any shortest simple path contains at most V1|V|-1 edges. Therefore, if there is no negative cycle reachable from the source, repeating edge relaxation V1|V|-1 times is sufficient to compute correct shortest distances.2

The relaxation rule for an edge (u,v)(u,v) with weight w(u,v)w(u,v) is:

if d[u]+w(u,v)<d[v], then set d[v]=d[u]+w(u,v)\text{if } d[u] + w(u,v) < d[v], \text{ then set } d[v] = d[u] + w(u,v)

After V1|V|-1 full passes over all edges, one more pass is used to test for a negative cycle.2 If any distance can still be improved, then a negative cycle is reachable, and no finite shortest path exists for affected vertices because the path cost can be driven downward without bound.2

The time complexity is:

O(VE)O(|V||E|)

which is slower than Dijkstra, but it is the correct general-purpose method when negative weights are allowed.3

Footnotes

  1. Bellman-Ford - finding shortest paths with negative weights - Detailed explanation of Bellman-Ford, repeated relaxation, and negative-cycle detection. 2 3 4 5

  2. Bellman–Ford algorithm - Wikipedia - Describes Bellman-Ford’s O(VE)O(|V||E|) runtime, handling of negative weights, and negative-cycle detection. 2 3 4 5

  3. Shortest Path Algorithm Comparison: Two Questions Decide - Concise comparison of BFS, Dijkstra, and Bellman-Ford by graph weight conditions and complexity.

How Bellman–Ford Handles Negative Edge Lengths

  1. 1
    Step 1

    Set the source distance to 00 and all other distances to infinity.2

    Footnotes

    1. Bellman-Ford - finding shortest paths with negative weights - Detailed explanation of Bellman-Ford, repeated relaxation, and negative-cycle detection.

    2. Bellman–Ford algorithm - Wikipedia - Describes Bellman-Ford’s O(VE)O(|V||E|) runtime, handling of negative weights, and negative-cycle detection.

  2. 2
    Step 2

    Scan every edge in the graph and apply the relaxation rule. Repeat this process exactly V1|V|-1 times because any shortest simple path uses at most V1|V|-1 edges.2

    Footnotes

    1. Bellman-Ford - finding shortest paths with negative weights - Detailed explanation of Bellman-Ford, repeated relaxation, and negative-cycle detection.

    2. Bellman–Ford algorithm - Wikipedia - Describes Bellman-Ford’s O(VE)O(|V||E|) runtime, handling of negative weights, and negative-cycle detection.

  3. 3
    Step 3

    Whenever a better distance is found, store the predecessor so that the shortest route can later be reconstructed.

  4. 4
    Step 4

    Run one additional pass over all edges. If any distance still decreases, then a reachable negative cycle exists, so a finite shortest path is not well-defined.2

    Footnotes

    1. Bellman-Ford - finding shortest paths with negative weights - Detailed explanation of Bellman-Ford, repeated relaxation, and negative-cycle detection.

    2. Bellman–Ford algorithm - Wikipedia - Describes Bellman-Ford’s O(VE)O(|V||E|) runtime, handling of negative weights, and negative-cycle detection.

  5. 5
    Step 5

    If no negative cycle is detected, return distances and predecessor paths. If a negative cycle exists, report that shortest paths are undefined for vertices reachable from that cycle.

Negative Cycles Make the Problem Ill-Defined

If a reachable cycle has total weight less than 00, a traveler could loop around it repeatedly and drive the path cost toward -\infty, so no finite shortest path exists.2

Footnotes

  1. Bellman-Ford - finding shortest paths with negative weights - Detailed explanation of Bellman-Ford, repeated relaxation, and negative-cycle detection.

  2. Bellman–Ford algorithm - Wikipedia - Describes Bellman-Ford’s O(VE)O(|V||E|) runtime, handling of negative weights, and negative-cycle detection.

Comparison of Shortest-Path Algorithms for City Routing

Relative asymptotic running-time forms for the three cases

Comparative Justification

The three algorithm choices are justified by the mathematical structure of the graph weights, not by superficial implementation preference.

1. Equal weights \rightarrow BFS

When all roads have the same cost, total path length is proportional to edge count. BFS explores in increasing number of edges from the source, so it is optimal and asymptotically cheaper than weighted algorithms.3

2. Nonnegative varying weights \rightarrow Dijkstra

When weights differ but remain nonnegative, a greedy frontier-expansion strategy is sound. The first time the minimum tentative vertex is extracted, its shortest distance is final.2 This makes Dijkstra both correct and efficient for realistic road lengths and travel times.

3. Negative weights \rightarrow Bellman–Ford

Negative edges invalidate Dijkstra’s greedy assumption. Bellman–Ford remains correct because it does not finalize nodes prematurely; instead, it allows improvements to propagate across the graph through repeated relaxation.3 It also adds the crucial ability to detect negative cycles.

A compact decision rule is:

Algorithm={BFS,if all weights are equalDijkstra,if w(e)0 for all eBellman-Ford,if some w(e)<0\text{Algorithm}= \begin{cases} \text{BFS}, & \text{if all weights are equal} \\ \text{Dijkstra}, & \text{if } w(e)\ge 0 \text{ for all } e \\ \text{Bellman-Ford}, & \text{if some } w(e)<0 \end{cases}

Footnotes

  1. Shortest Path Algorithm Comparison: Two Questions Decide - Concise comparison of BFS, Dijkstra, and Bellman-Ford by graph weight conditions and complexity.

  2. Understanding connection between minimum spanning tree, shortest path, breadth first and depth first traversal - Summarizes the CLRS statement that BFS gives shortest-path distances in unweighted graphs.

  3. Dijkstra's algorithm - Wikipedia - Notes that BFS is a special case of Dijkstra on unweighted graphs.

  4. Dijkstra's algorithm - Wikipedia - Describes Dijkstra’s purpose, nonnegative-weight requirement, and standard complexity.

  5. Chapter 12 Shortest Paths (CMU lecture notes) - Explains why Dijkstra works for nonnegative edges and fails with negative ones. 2

  6. Bellman-Ford - finding shortest paths with negative weights - Detailed explanation of Bellman-Ford, repeated relaxation, and negative-cycle detection.

  7. Bellman–Ford algorithm - Wikipedia - Describes Bellman-Ford’s O(VE)O(|V||E|) runtime, handling of negative weights, and negative-cycle detection.

Best when every road segment has identical cost. Computes shortest paths by number of edges in O(V+E)O(|V|+|E|) time.2

Footnotes

  1. Shortest Path Algorithm Comparison: Two Questions Decide - Concise comparison of BFS, Dijkstra, and Bellman-Ford by graph weight conditions and complexity.

  2. Understanding connection between minimum spanning tree, shortest path, breadth first and depth first traversal - Summarizes the CLRS statement that BFS gives shortest-path distances in unweighted graphs.

Shortest-Path Decision Workflow for a City Graph

Model the city

Step 1

Represent locations as vertices and roads as weighted or unweighted edges."

Inspect edge weights

Step 2

Determine whether all road lengths are equal, merely nonnegative, or possibly negative."

Select the algorithm

Step 3

Use BFS for equal weights, Dijkstra for nonnegative weights, and Bellman-Ford for negative weights.3"

Footnotes

  1. Shortest Path Algorithm Comparison: Two Questions Decide - Concise comparison of BFS, Dijkstra, and Bellman-Ford by graph weight conditions and complexity.

  2. Bellman-Ford - finding shortest paths with negative weights - Detailed explanation of Bellman-Ford, repeated relaxation, and negative-cycle detection.

  3. Dijkstra's algorithm - Wikipedia - Describes Dijkstra’s purpose, nonnegative-weight requirement, and standard complexity.

Compute distances

Step 4

Run the selected single-source shortest-path algorithm from the chosen source location."

Validate edge-case behavior

Step 5

If Bellman-Ford detects a negative cycle, report that finite shortest paths are undefined for impacted vertices.2"

Footnotes

  1. Bellman-Ford - finding shortest paths with negative weights - Detailed explanation of Bellman-Ford, repeated relaxation, and negative-cycle detection.

  2. Bellman–Ford algorithm - Wikipedia - Describes Bellman-Ford’s O(VE)O(|V||E|) runtime, handling of negative weights, and negative-cycle detection.

Common Questions and Edge Cases

Final Answer

For a city graph:

  1. If all roads have equal length, use BFS, because shortest distance is equivalent to the fewest number of roads traversed.2
  2. If roads have varying lengths but none are negative, use Dijkstra’s algorithm, because its greedy selection is correct under nonnegative weights and it is efficient.2
  3. If some roads have negative lengths, use Bellman–Ford, because it correctly handles negative edges and can detect negative cycles where shortest paths are not well-defined.2

Thus, the algorithm choice is determined by the weight properties of the road network graph, and each recommendation follows directly from the correctness conditions of the corresponding shortest-path algorithm.3

Footnotes

  1. Understanding connection between minimum spanning tree, shortest path, breadth first and depth first traversal - Summarizes the CLRS statement that BFS gives shortest-path distances in unweighted graphs.

  2. Dijkstra's algorithm - Wikipedia - Notes that BFS is a special case of Dijkstra on unweighted graphs.

  3. Dijkstra's algorithm - Wikipedia - Describes Dijkstra’s purpose, nonnegative-weight requirement, and standard complexity. 2

  4. Chapter 12 Shortest Paths (CMU lecture notes) - Explains why Dijkstra works for nonnegative edges and fails with negative ones.

  5. Bellman-Ford - finding shortest paths with negative weights - Detailed explanation of Bellman-Ford, repeated relaxation, and negative-cycle detection. 2

  6. Bellman–Ford algorithm - Wikipedia - Describes Bellman-Ford’s O(VE)O(|V||E|) runtime, handling of negative weights, and negative-cycle detection.

  7. Shortest Path Algorithm Comparison: Two Questions Decide - Concise comparison of BFS, Dijkstra, and Bellman-Ford by graph weight conditions and complexity.

Knowledge Check

Question 1 of 4
Q1Single choice

If every road in a city graph has the same length, which algorithm is the best choice for shortest paths?

Explore Related Topics

1

Dijkstra's Algorithm

Dijkstra's algorithm finds the shortest‑path distances from a single source to all reachable vertices in a weighted graph whose edge weights are non‑negative, using a greedy selection of the minimum‑distance unsettled vertex and edge relaxation.

  • Keeps a tentative distance array and a min‑priority queue; extracting the smallest distance finalizes that vertex’s shortest path.
  • Correct only for non‑negative edges; negative weights invalidate the greedy invariant.
  • With an adjacency‑list and binary heap the time is O((V+E) log V); matrix scans give O(V²) and Fibonacci heaps can achieve O(E + V log V).
  • Storing a predecessor array allows reconstruction of actual shortest paths and early termination when a specific target is settled.
  • Fundamental in routing, navigation, and as a subroutine in many larger graph algorithms.
2

Negative Weight Cycle and the Bellman-Ford Algorithm for Single-Source Shortest Distance

Negative weight cycles are cycles whose total edge weight is negative, and the Bellman‑Ford algorithm computes single‑source shortest distances while detecting such cycles.

  • A reachable negative weight cycle makes the shortest‑distance problem undefined because repeated traversal can lower the path cost without bound.
  • Bellman‑Ford initializes distances, relaxes all edges |V|‑1 times, then performs one extra pass to detect any further relaxation.
  • It correctly handles negative edges but reports failure when a reachable negative cycle exists.
  • The algorithm runs in O(V E) time and uses O(V) extra space.
  • Vertices unreachable from the source keep a distance of ∞.
3

Complexity Analysis: Best Case, Worst Case, and Average Case

The material introduces best‑case, worst‑case, and average‑case complexity as three distinct functions describing an algorithm’s running time on inputs of size nn, explains how they are formally defined, and shows why worst‑case analysis is usually preferred.

  • Best case: Tbest(n)=minIInT(I)T_{\text{best}}(n)=\min_{I\in\mathcal I_n} T(I), the minimum time over all inputs of size nn.
  • Worst case: Tworst(n)=maxIInT(I)T_{\text{worst}}(n)=\max_{I\in\mathcal I_n} T(I), giving a guaranteed upper bound.
  • Average case: Tavg(n)=IInP(I)T(I)T_{\text{avg}}(n)=\sum_{I\in\mathcal I_n}P(I)\,T(I), requiring an explicit input probability model.
  • Linear search illustrates the three cases: Θ(1)\Theta(1) best, Θ(n)\Theta(n) worst, and Θ(n)\Theta(n) average (expected n+12\frac{n+1}{2} comparisons).
  • Worst‑case analysis is favored because it needs no probabilistic assumptions and ensures reliability for all inputs, especially in real‑time or safety‑critical systems.
Chat with Kiro