Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

9. Shortest paths on terrain: breadth-first search, Dijkstra and A*

School of Engineering, Nazarbayev University

How does an autonomous Mars rover or subsea pipeline router thread through a rugged mountain saddle pass to find the exact global minimum-energy corridor—while inspecting less than a third of the terrain explored by blind Dijkstra? The answer is Hart, Nilsson & Raphael’s (1968) A∗A^* Search (Mental Move #18, Guide Search with an Admissible Lower Bound): priority-ordering frontier states by f(u)=g(u)+h(u)f(u) = g(u) + h(u), where g(u)g(u) is exact cost-so-far and h(u)h(u) is a physically admissible (0≤h(u)≤h∗(u)0 \leq h(u) \leq h^*(u)) lower bound on remaining cost. In this lecture, you will route across 2-D mountain topography (constants_benchmarks.make_topographic_terrain) using greedy_heuristic_search.grid_shortest_path_search, contrast unweighted BFS, blind Dijkstra, admissible A∗A^*, and bounded-suboptimal Weighted A∗A^*, compare 4-neighbor taxicab vs. 8-neighbor Euclidean geometry, and build a Bidirectional Dijkstra solver.

Learning objectives

  1. Contrast unweighted Breadth-First Search (method='bfs') against uniform-cost Dijkstra (method='dijkstra') on variable-elevation terrain (constants_benchmarks.make_topographic_terrain).

  2. Prove why an admissible (h(u)≤h∗(u)h(u) \leq h^*(u)) and consistent (h(u)≤c(u,v)+h(v)h(u) \leq c(u,v) + h(v)) heuristic guarantees exact optimal paths in grid_shortest_path_search(method='astar') while focusing wavefront expansions toward the goal.

  3. Quantify Pohl’s Weighted A∗A^* speed-vs.-optimality Pareto trade-off (C(w)≤w C∗C(w) \leq w\,C^* for w≥1w \geq 1) and eliminate 4-neighbor Manhattan staircase bias using 8-neighbor Euclidean geometry (allow_diagonal=True).

  4. Implement Bidirectional Dijkstra on asymmetric cell-entry grids and combine pairwise A∗A^* terrain costs with exact Held–Karp subset DP for multi-waypoint autonomous rover routing.

Time: about 60 min

1. Unweighted BFS vs. Variable-Cost Dijkstra on Mountain Topography

Suppose a 2-D elevation map z(r,c)z(r, c) induces a positive cell-traversal energy cost C(r,c)≥cmin⁡>0C(r, c) \geq c_{\min} > 0 (for example, C=1+9.5 z~2C = 1 + 9.5\,\tilde{z}^2 penalizing steep alpine ridges). Moving from cell uu to neighbor vv incurs edge weight w(u→v)=ℓ(u,v) C(v)w(u \to v) = \ell(u, v)\, C(v), where step length ℓ(u,v)=1\ell(u, v) = 1 for 4-cardinal moves and 2\sqrt{2} for diagonal moves.

  • Breadth-First Search (method="bfs"): Explores FIFO layers by hop count, finding a path with minimum number of steps while ignoring C(v)C(v), so its path may cross the highest ridges.

  • Dijkstra’s Algorithm (method="dijkstra"): Expands open cells in increasing order of exact accumulated cost g(u)g(u) via a binary min-heap. Because all edge weights w(u→v)>0w(u \to v) > 0, the first time the goal gg pops from the priority queue, g(goal)=C∗g(\mathrm{goal}) = C^* is provably globally minimum.


Demonstration 1: Step-minimal BFS against energy-minimal Dijkstra on mountain terrain
=====================================================================================
Mental Move #18 (Guide Search with an Admissible Lower Bound): 0 <= h(u) <= h*(u) guarantees optimal path
Unweighted BFS (min hops) :  84 steps | Terrain Energy Cost = 135.84
Exact Dijkstra (min cost) :  84 steps | Terrain Energy Cost = 107.35 (saves 21.0% energy)
<Figure size 792x550 with 2 Axes>

Figure 9.1. Paths across the synthetic terrain (colour: elevation). Breadth-first search (dashed) minimises the number of steps and crosses high ground, cost 135.8; Dijkstra (solid) minimises the energy cost, 107.4, with the same 84 steps.

What Demonstration 1 shows. Both paths have 84 steps, but the BFS path crosses the ridge (135.8 energy units), whereas Dijkstra finds a lower route (107.3 energy units), 21 % less energy. Dijkstra has no information about where the goal lies, so its frontier grows in all directions until every cell with g(u)<C∗g(u) < C^* has been expanded.


2. Admissible A∗A^* Search: a Focused Search with the Same Optimal Cost

Hart, Nilsson & Raphael (1968) guided the priority queue using f(u)=g(u)+h(u)f(u) = g(u) + h(u). Suppose cmin⁡=min⁡vC(v)>0c_{\min} = \min_v C(v) > 0 is the cheapest traversal cost anywhere on the map. Because every 4-neighbor path from u=(r,c)u = (r, c) to goal=(rg,cg)\mathrm{goal} = (r_g, c_g) takes at least ∣rg−r∣+∣cg−c∣|r_g - r| + |c_g - c| steps (or Euclidean distance Δr2+Δc2\sqrt{\Delta r^2 + \Delta c^2} for 8-neighbor moves), each costing at least cmin⁡c_{\min}:

h(u)=cmin⁡ dgeom(u,goal)  ≤  h∗(u)(admissible lower bound)(2.1)h(u) = c_{\min}\, d_{\mathrm{geom}}(u, \mathrm{goal}) \;\leq\; h^*(u) \qquad \text{(admissible lower bound)} \tag{2.1}

Why Admissibility Guarantees Exact Optimality: Suppose A∗A^* pops goal\mathrm{goal} with cost g(goal)=f(goal)g(\mathrm{goal}) = f(\mathrm{goal}) (since h(goal)=0h(\mathrm{goal}) = 0). Could an unexpanded frontier node uu lie on a strictly cheaper true path of cost C∗<g(goal)C^* < g(\mathrm{goal})? On that optimal path, f(u)=g(u)+h(u)≤g∗(u)+h∗(u)=C∗<f(goal)f(u) = g(u) + h(u) \leq g^*(u) + h^*(u) = C^* < f(\mathrm{goal})—meaning uu would have popped before goal\mathrm{goal}. Contradiction.


Demonstration 2: Dijkstra against admissible A* search wavefront geometry
=========================================================================
Saddle-Pass Corridor (36, 6) -> (42, 42):
  Dijkstra        : Cost = 63.314476 | Expanded = 1704 cells
  Admissible A*   : Cost = 63.314476 | Expanded =  532 cells (31.2% of Dijkstra — 3.20x fewer)
<Figure size 1045x451 with 2 Axes>

Figure 9.2. Cells expanded on the route from (36, 6) to (42, 42). (a) Dijkstra expands 1,704 cells in all directions. (b) A* with the admissible heuristic expands 532 cells and finds the same path (line).

What Demonstration 2 shows. In the two heatmaps, Dijkstra expands cells on every side of the start (1,704 expansions), whereas admissible A∗A^* (w = 1.0) keeps to a narrow region along the corridor (532 expansions, 31.2 % of Dijkstra) and returns the same cost, 63.314476.


3. Bounded-Suboptimal Weighted A∗A^* (fw(u)=g(u)+w h(u)f_w(u) = g(u) + w\,h(u))

In real-time robotics on 106-cell maps, what if even admissible A∗A^* (w=1w = 1) expands too many nodes because cmin⁡c_{\min} is much smaller than typical mountain terrain costs? Pohl (1970) introduced Weighted A∗A^* with w≥1w \geq 1: inflating h(u)h(u) by ww sacrifices exact optimality in exchange for a provable worst-case suboptimality bound:

1  ≤  CWA∗(w)C∗  ≤  w(∀w≥1, for admissible h)(3.1)1 \;\leq\; \frac{C_{\mathrm{WA}^*}(w)}{C^*} \;\leq\; w \qquad (\forall w \geq 1,\text{ for admissible } h) \tag{3.1}

Demonstration 3: Weighted A* Pareto curve and verification of Pohl's w-suboptimality bound
==========================================================================================
Weight w | Nodes Expanded | Path Cost C(w) | Actual C(w)/C* | Pohl Bound w
--------------------------------------------------------------------------
    0.00 |           2447 |        107.354 |         1.0000 |         1.00
    0.50 |           1955 |        107.354 |         1.0000 |         1.00
    1.00 |           1564 |        107.354 |         1.0000 |         1.00
    1.25 |           1237 |        107.354 |         1.0000 |         1.25
    1.50 |            682 |        107.580 |         1.0021 |         1.50
    2.00 |            163 |        107.580 |         1.0021 |         2.00
    2.50 |            121 |        109.060 |         1.0159 |         2.50
    3.00 |            108 |        116.720 |         1.0872 |         3.00
    4.00 |             99 |        128.688 |         1.1987 |         4.00
<Figure size 1012x429 with 2 Axes>

Figure 9.3. Weighted A* on the route of Demonstration 1. (a) Expanded cells against the weight ww; the vertical line marks w=1w = 1. (b) Cost ratio C(w)/C∗C(w)/C^* (solid) against Pohl’s bound ww (dashed): the actual loss is at most 20 % at w=4w = 4, far below the bound.

What Demonstration 3 shows. the bound is far from tight here. At w=2.0w = 2.0 it guarantees C≤2.0 C∗C \leq 2.0\,C^*, while the actual cost rises by 0.21 % (ratio 1.0021) and the number of expansions falls from 2,447 at w = 0 to 163.


4. 4-Neighbor Manhattan Staircase Bias vs. 8-Neighbor Euclidean Geometry

On a 4-connected grid (allow_diagonal=False), travelling diagonally across a flat L×LL \times L plain requires 2L2L orthogonal zig-zag steps instead of 2 L\sqrt{2}\,L—a path 41.4 %41.4\,\% too long. Enabling 8-neighbor diagonal moves (allow_diagonal=True, step length 2\sqrt{2}, paired with Euclidean heuristic h(u)=cmin⁡Δr2+Δc2h(u) = c_{\min}\sqrt{\Delta r^2 + \Delta c^2}) reduces this bias: on the flat plain the 8-neighbour path has the exact length 202=28.28420\sqrt{2} = 28.284, and on the mountain terrain its cost, 93.72, is 12.7 % below the 4-neighbour cost, 107.35.


Demonstration 4: 4-neighbor taxicab staircase bias against 8-neighbor diagonal routing
======================================================================================
Flat 20x20 diagonal : 4-Neighbor = 40.000 vs. 8-Neighbor = 28.284 (exact 20*sqrt(2))
Mountain (6,6)->(48,48): 4-Neighbor A* = 107.35 vs. 8-Neighbor A* = 93.72 (exact = 93.72)
<Figure size 770x506 with 1 Axes>

Figure 9.4. A* paths with 4 neighbours and the Manhattan heuristic (dashed, cost 107.4) and with 8 neighbours and the Euclidean heuristic (solid, cost 93.7). The 4-neighbour path has to move in a staircase.

Inside the algorithm

Even without a heuristic (h≡0h \equiv 0), the search region of Dijkstra can be reduced by searching from both ends. Two disks of radius R/2R/2 around start and goal have combined area 2⋅π(R/2)2=12πR22 \cdot \pi (R/2)^2 = \frac{1}{2} \pi R^2—half the area of one disk of radius RR.

Two details matter in bidirectional Dijkstra on our cell-entry cost grid (w(u→v)=ℓ(u,v) C(v)w(u \to v) = \ell(u, v)\, C(v)):

  1. Forward search relaxes outgoing edges u→vu \to v with weight ℓ(u,v)C(v)\ell(u,v) C(v); backward search from goal relaxes incoming forward edges u→vu \to v (stepping backward from vv to uu adds ℓ(u,v)C(v)\ell(u,v) C(v)), so at any meeting cell mm, gF(m)+gB(m)g_F(m) + g_B(m) equals the exact path cost with zero double-counting of C(m)C(m).

  2. Search terminates only when min⁡(openF)+min⁡(openB)≥μ∗\min(\mathrm{open}_F) + \min(\mathrm{open}_B) \geq \mu^*, where μ∗\mu^* is the best complete path cost seen across any touched pair. We inspect grid_shortest_path_search and verify bidirectional_dijkstra_grid.

Check against the library


Inside the algorithm: grid_shortest_path_search and exact bidirectional Dijkstra
================================================================================
def grid_shortest_path_search(
    cost_grid: np.ndarray,
    start: tuple[int, int],
    goal: tuple[int, int],
    method: str = "astar",
    heuristic_weight: float = 1.0,
    allow_diagonal: bool = False,
) -> dict:
    """Find optimal grid path via 'bfs' (unit steps), 'dijkstra', or 'astar' (admissible at heuristic_weight <= 1)."""
    grid = np.asarray(cost_grid, dtype=float)
    if grid.ndim != 2 or grid.size == 0:
        raise ValueError("cost_grid must be a non-empty 2-D array (positive finite costs, inf for obstacles).")
    h, w = grid.shape
    sr, sc = int(start[0]), int(start[1])
    gr, gc = int(goal[0]), int(goal[1])
    if not (0 <= sr < h and 0 <= sc < w and 0 <= gr < h and 0 <= gc < w):
        raise ValueError("start and goal must lie inside cost_grid bounds.")
    if not (math.isfinite(grid[sr, sc]) and math.isfinite(grid[gr, gc])):
        empty_vo = np.full((h, w), -1, dtype=int)
        return {"found": False, "path": [], "total_cost": math.inf, "nodes_expanded": 0, "visited_order": empty_vo}

    finite_vals = grid[np.isfinite(grid)]
    if finite_vals.size == 0 or np.any(finite_vals <= 0.0):
        raise ValueError("All passable cells in cost_grid must have strictly positive cost > 0.")
    c_min = float(np.min(finite_vals))

    key = method.strip().lower()
    if key not in ("bfs", "dijkstra", "astar"):
        raise ValueError(f"Unsupported search method {method!r}; choose 'bfs', 'dijkstra', or 'astar'.")
    if heuristic_weight < 0.0:
        raise ValueError("heuristic_weight must be >= 0.")

    moves = [(-1, 0, 1.0), (1, 0, 1.0), (0, -1, 1.0), (0, 1, 1.0)]
    if allow_diagonal:
        s2 = math.sqrt(2.0)
        moves.extend([(-1, -1, s2), (-1, 1, s2), (1, -1, s2), (1, 1, s2)])

    visited_order = np.full((h, w), -1, dtype=int)
    parent_r = np.full((h, w), -1, dtype=int)
    parent_c = np.full((h, w), -1, dtype=int)

    if key == "bfs":
        q: deque[tuple[int, int]] = deque([(sr, sc)])
        seen = np.zeros((h, w), dtype=bool)
        seen[sr, sc] = True
        exp_cnt = 0
        found = False
        while q:
            r, c = q.popleft()
            visited_order[r, c] = exp_cnt
            exp_cnt += 1
            if (r, c) == (gr, gc):
                found = True
                break
            for dr, dc, _ in moves:
                nr, nc = r + dr, c + dc
                if 0 <= nr < h and 0 <= nc < w and not seen[nr, nc] and math.isfinite(grid[nr, nc]):
                    seen[nr, nc] = True
                    parent_r[nr, nc] = r
                    parent_c[nr, nc] = c
                    q.append((nr, nc))
        if not found:
            return {
                "found": False,
                "path": [],
                "total_cost": math.inf,
                "nodes_expanded": exp_cnt,
                "visited_order": visited_order,
            }
        path: list[tuple[int, int]] = []
        cr, cc = gr, gc
        while (cr, cc) != (sr, sc):
            path.append((cr, cc))
            cr, cc = int(parent_r[cr, cc]), int(parent_c[cr, cc])
        path.append((sr, sc))
        path.reverse()
        cost_sum = sum(float(grid[r, c]) for r, c in path[1:])
        return {
            "found": True,
            "path": path,
            "total_cost": cost_sum,
            "nodes_expanded": exp_cnt,
            "visited_order": visited_order,
        }

    def _heuristic(r: int, c: int) -> float:
        if key == "dijkstra" or heuristic_weight == 0.0:
            return 0.0
        dr = abs(gr - r)
        dc = abs(gc - c)
        dist_lb = (math.hypot(dr, dc) if allow_diagonal else float(dr + dc))
        return float(heuristic_weight) * c_min * dist_lb

    g_cost = np.full((h, w), math.inf, dtype=float)
    closed = np.zeros((h, w), dtype=bool)
    g_cost[sr, sc] = 0.0
    tie = 0
    pq: list[tuple[float, int, int, int]] = [(_heuristic(sr, sc), tie, sr, sc)]
    exp_cnt = 0
    found = False

    while pq:
        _, _, r, c = heapq.heappop(pq)
        if closed[r, c]:
            continue
        closed[r, c] = True
        visited_order[r, c] = exp_cnt
        exp_cnt += 1
        if (r, c) == (gr, gc):
            found = True
            break
        base_g = g_cost[r, c]
        for dr, dc, step_len in moves:
            nr, nc = r + dr, c + dc
            if 0 <= nr < h and 0 <= nc < w and not closed[nr, nc] and math.isfinite(grid[nr, nc]):
                ng = base_g + step_len * float(grid[nr, nc])
                if ng < g_cost[nr, nc] - 1e-13:
                    g_cost[nr, nc] = ng
                    parent_r[nr, nc] = r
                    parent_c[nr, nc] = c
                    tie += 1
                    heapq.heappush(pq, (ng + _heuristic(nr, nc), tie, nr, nc))

    if not found:
        return {
            "found": False,
            "path": [],
            "total_cost": math.inf,
            "nodes_expanded": exp_cnt,
            "visited_order": visited_order,
        }

    path = []
    cr, cc = gr, gc
    while (cr, cc) != (sr, sc):
        path.append((cr, cc))
        cr, cc = int(parent_r[cr, cc]), int(parent_c[cr, cc])
    path.append((sr, sc))
    path.reverse()
    return {
        "found": True,
        "path": path,
        "total_cost": float(g_cost[gr, gc]),
        "nodes_expanded": exp_cnt,
        "visited_order": visited_order,
    }

Route (10, 10) -> (22, 22): Cost = 28.451521 (exact match) | Uni-Dijkstra = 786 vs. Bi-Dijkstra = 478 nodes
Route (14, 14) -> (24, 24): Cost = 33.265644 (exact match) | Uni-Dijkstra = 953 vs. Bi-Dijkstra = 499 nodes
Route (36, 36) -> (48, 48): Cost = 24.128805 (exact match) | Uni-Dijkstra = 747 vs. Bi-Dijkstra = 459 nodes

Exercises

Worked solutions are in 09_solutions.ipynb. The cell below the list is a short self-check to start from.

  1. Verify a result. Across every directed 4-neighbor and 8-neighbor edge (u→v)(u \to v) of make_topographic_terrain(56, 56, seed=42), verify heuristic consistency h(u)≤w(u→v)+h(v)h(u) \leq w(u \to v) + h(v) and h(goal)=0h(\mathrm{goal}) = 0, and verify that f(uk)=g(uk)+h(uk)f(u_k) = g(u_k) + h(u_k) is monotonically non-decreasing along admissible A∗A^*'s expansion order.

  2. Find how it fails. Verify ValueError guards on grid_shortest_path_search, then demonstrate quantitatively (a) how replacing cmin⁡c_{\min} with cmeanc_{\mathrm{mean}} or cmax⁡c_{\max} in h(u)h(u) breaks admissibility and returns a suboptimal path, and (b) how pairing a Manhattan heuristic ∣Δr∣+∣Δc∣|\Delta r| + |\Delta c| with 8-neighbor diagonal moves returns a strictly suboptimal route.

  3. Implement it yourself. Implement multi_waypoint_terrain_planner(cost_grid, depot, waypoints) combining pairwise 8-neighbor admissible A∗A^* shortest paths with exact Held–Karp subset DP (O(K22K)\mathcal{O}(K^2 2^K)) to route an autonomous rover from depot through K=6K = 6 geological targets and back to depot. Verify exact cost agreement against all 6!=7206! = 720 permutations and compare against greedy Nearest-Neighbor.


Self-check for the exercises
============================
All checks passed.