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) Search (Mental Move #18, Guide Search with an Admissible Lower Bound): priority-ordering frontier states by , where is exact cost-so-far and is a physically admissible () 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 , and bounded-suboptimal Weighted , compare 4-neighbor taxicab vs. 8-neighbor Euclidean geometry, and build a Bidirectional Dijkstra solver.
Learning objectives¶
Contrast unweighted Breadth-First Search (
method='bfs') against uniform-cost Dijkstra (method='dijkstra') on variable-elevation terrain (constants_benchmarks.make_topographic_terrain).Prove why an admissible () and consistent () heuristic guarantees exact optimal paths in
grid_shortest_path_search(method='astar')while focusing wavefront expansions toward the goal.Quantify Pohl’s Weighted speed-vs.-optimality Pareto trade-off ( for ) and eliminate 4-neighbor Manhattan staircase bias using 8-neighbor Euclidean geometry (
allow_diagonal=True).Implement Bidirectional Dijkstra on asymmetric cell-entry grids and combine pairwise terrain costs with exact Held–Karp subset DP for multi-waypoint autonomous rover routing.
Time: about 60 min
try: # use the installed package, or the copy in this repository
import engthink
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engthink" / "__init__.py").exists():
sys.path.insert(0, str(_root))
break
else: # on Google Colab: install from GitHub
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"git+https://github.com/ktwyw/engthink.git"], check=True)
import engthink
import inspect
import math
import numpy as np
import matplotlib.pyplot as plt
from engthink import (constants_benchmarks, divide_spatial, dynamic_optimality, emergence_verification,
greedy_heuristic_search, information_streams, invariants_complexity, reductions_constraints,
representation_scaling)
from engthink.plotting import label_panels, log_ticks, panel_label, use_style
use_style()
def show_source(obj):
"""Return the source code of a library function or class."""
return inspect.getsource(obj)
def heading(text):
print(f"\n{text}\n" + "=" * len(text))1. Unweighted BFS vs. Variable-Cost Dijkstra on Mountain Topography¶
Suppose a 2-D elevation map induces a positive cell-traversal energy cost (for example, penalizing steep alpine ridges). Moving from cell to neighbor incurs edge weight , where step length for 4-cardinal moves and for diagonal moves.
Breadth-First Search (
method="bfs"): Explores FIFO layers by hop count, finding a path with minimum number of steps while ignoring , so its path may cross the highest ridges.Dijkstra’s Algorithm (
method="dijkstra"): Expands open cells in increasing order of exact accumulated cost via a binary min-heap. Because all edge weights , the first time the goal pops from the priority queue, is provably globally minimum.
heading("Demonstration 1: Step-minimal BFS against energy-minimal Dijkstra on mountain terrain")
mm18 = [m for m in constants_benchmarks.MENTAL_MOVES_DB if m["id"] == 18][0]
print(f"Mental Move #{mm18['id']} ({mm18['name']}): {mm18['invariant']}")
terrain = constants_benchmarks.make_topographic_terrain(nx=56, ny=56, seed=42)
elev_m = terrain["elevation_m"]
cost_grid = terrain["cost_grid"]
start_ab, goal_ab = (6, 6), (48, 48)
res_bfs = greedy_heuristic_search.grid_shortest_path_search(cost_grid, start_ab, goal_ab, method="bfs")
res_dijk = greedy_heuristic_search.grid_shortest_path_search(cost_grid, start_ab, goal_ab, method="dijkstra")
assert res_bfs["found"] and res_dijk["found"]
assert len(res_bfs["path"]) <= len(res_dijk["path"]) # BFS minimizes step count (85 cells = 84 Manhattan steps)
assert res_dijk["total_cost"] < 0.80 * res_bfs["total_cost"] # Dijkstra saves >20% traversal energy via the saddle pass
print(f"Unweighted BFS (min hops) : {len(res_bfs['path']) - 1:3d} steps | Terrain Energy Cost = {res_bfs['total_cost']:.2f}")
print(f"Exact Dijkstra (min cost) : {len(res_dijk['path']) - 1:3d} steps | Terrain Energy Cost = {res_dijk['total_cost']:.2f} (saves {100.0 * (1.0 - res_dijk['total_cost']/res_bfs['total_cost']):.1f}% energy)")
bfs_rc = np.array(res_bfs["path"])
dijk_rc = np.array(res_dijk["path"])
fig, ax = plt.subplots(figsize=(7.2, 5.0))
im = ax.imshow(elev_m, origin="lower", cmap="terrain")
ax.contour(elev_m, levels=8, colors="black", linewidths=0.45, alpha=0.45)
ax.plot(bfs_rc[:, 1], bfs_rc[:, 0], lw=2.3, ls="--", color="#C0392B", label=f"Unweighted BFS (cost = {res_bfs['total_cost']:.1f})")
ax.plot(dijk_rc[:, 1], dijk_rc[:, 0], lw=2.6, color="#19D3C5", label=f"Optimal Dijkstra (cost = {res_dijk['total_cost']:.1f})")
ax.scatter([start_ab[1], goal_ab[1]], [start_ab[0], goal_ab[0]], s=75, c=["white", "#F2C744"], edgecolors="black", zorder=5)
ax.set_xlabel("Grid column $c$")
ax.set_ylabel("Grid row $r$")
ax.set_title("Fewest steps (BFS) against least cost (Dijkstra)")
ax.grid(False)
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.17), ncol=1, fontsize=8.5)
fig.colorbar(im, ax=ax, label="Elevation [m]")
plt.show()
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 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 has been expanded.
2. Admissible Search: a Focused Search with the Same Optimal Cost¶
Hart, Nilsson & Raphael (1968) guided the priority queue using . Suppose is the cheapest traversal cost anywhere on the map. Because every 4-neighbor path from to takes at least steps (or Euclidean distance for 8-neighbor moves), each costing at least :
Why Admissibility Guarantees Exact Optimality: Suppose pops with cost (since ). Could an unexpanded frontier node lie on a strictly cheaper true path of cost ? On that optimal path, —meaning would have popped before . Contradiction.
heading("Demonstration 2: Dijkstra against admissible A* search wavefront geometry")
start_pass, goal_pass = (36, 6), (42, 42)
dijk_pass = greedy_heuristic_search.grid_shortest_path_search(
cost_grid, start_pass, goal_pass, method="dijkstra", allow_diagonal=False
)
astar_pass = greedy_heuristic_search.grid_shortest_path_search(
cost_grid, start_pass, goal_pass, method="astar", heuristic_weight=1.0, allow_diagonal=False
)
# Exact global optimality preserved to floating-point precision, with < 1/3 the node expansions
assert np.isclose(astar_pass["total_cost"], dijk_pass["total_cost"], atol=1e-12)
exp_ratio = astar_pass["nodes_expanded"] / dijk_pass["nodes_expanded"]
assert exp_ratio < 1.0 / 3.0
# Also verify exact parity on the full cross-ridge route (6,6) -> (48,48):
astar_ab = greedy_heuristic_search.grid_shortest_path_search(cost_grid, start_ab, goal_ab, method="astar", heuristic_weight=1.0)
assert np.isclose(astar_ab["total_cost"], res_dijk["total_cost"], atol=1e-12)
assert astar_ab["nodes_expanded"] < res_dijk["nodes_expanded"]
print(f"Saddle-Pass Corridor {start_pass} -> {goal_pass}:")
print(f" Dijkstra : Cost = {dijk_pass['total_cost']:.6f} | Expanded = {dijk_pass['nodes_expanded']:4d} cells")
print(f" Admissible A* : Cost = {astar_pass['total_cost']:.6f} | Expanded = {astar_pass['nodes_expanded']:4d} cells ({100.0 * exp_ratio:.1f}% of Dijkstra — {1.0/exp_ratio:.2f}x fewer)")
vo_dijk = np.ma.masked_where(dijk_pass["visited_order"] < 0, dijk_pass["visited_order"])
vo_astar = np.ma.masked_where(astar_pass["visited_order"] < 0, astar_pass["visited_order"])
p_pass = np.array(astar_pass["path"])
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.5, 4.1))
ax1.contourf(elev_m, levels=12, cmap="Greys", alpha=0.35)
ax1.imshow(vo_dijk, origin="lower", cmap="plasma", alpha=0.82)
ax1.plot(p_pass[:, 1], p_pass[:, 0], color="#19D3C5", lw=2.3)
ax1.set_title(f"Dijkstra ({dijk_pass['nodes_expanded']} expanded)")
ax1.set_xlabel("Column $c$")
ax1.set_ylabel("Row $r$")
ax1.grid(False)
ax2.contourf(elev_m, levels=12, cmap="Greys", alpha=0.35)
ax2.imshow(vo_astar, origin="lower", cmap="plasma", alpha=0.82)
ax2.plot(p_pass[:, 1], p_pass[:, 0], color="#19D3C5", lw=2.3)
ax2.set_title(f"A* ({astar_pass['nodes_expanded']} expanded)")
ax2.set_xlabel("Column $c$")
ax2.set_ylabel("Row $r$")
ax2.grid(False)
label_panels(fig)
plt.show()
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 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 (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 ()¶
In real-time robotics on 106-cell maps, what if even admissible () expands too many nodes because is much smaller than typical mountain terrain costs? Pohl (1970) introduced Weighted with : inflating by sacrifices exact optimality in exchange for a provable worst-case suboptimality bound:
heading("Demonstration 3: Weighted A* Pareto curve and verification of Pohl's w-suboptimality bound")
weights_w = np.array([0.0, 0.5, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0, 4.0])
costs_w = np.zeros_like(weights_w)
nodes_w = np.zeros(weights_w.size, dtype=int)
for idx, w_val in enumerate(weights_w):
rw = greedy_heuristic_search.grid_shortest_path_search(
cost_grid, start_ab, goal_ab, method="astar", heuristic_weight=float(w_val)
)
costs_w[idx] = rw["total_cost"]
nodes_w[idx] = rw["nodes_expanded"]
c_star = costs_w[0]
ratios_w = costs_w / c_star
# 1. For every w in [0, 1], heuristic w*h(u) remains admissible, so C(w) == C* to machine precision
assert np.allclose(costs_w[weights_w <= 1.0], c_star, atol=1e-12)
# 2. For every w >= 1, Pohl's bound 1 <= C(w)/C* <= w holds strictly
mask_ge1 = weights_w >= 1.0
assert np.all((ratios_w[mask_ge1] >= 1.0 - 1e-12) & (ratios_w[mask_ge1] <= weights_w[mask_ge1] + 1e-12))
assert nodes_w[-1] < 0.15 * nodes_w[0]
print(f"{'Weight w':>8s} | {'Nodes Expanded':>14s} | {'Path Cost C(w)':>14s} | {'Actual C(w)/C*':>14s} | {'Pohl Bound w':>12s}")
print("-" * 74)
for w_v, n_v, c_v, r_v in zip(weights_w, nodes_w, costs_w, ratios_w):
ub = max(1.0, float(w_v))
print(f"{w_v:8.2f} | {n_v:14d} | {c_v:14.3f} | {r_v:14.4f} | {ub:12.2f}")
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.2, 3.9))
ax1.plot(weights_w, nodes_w, marker="o", lw=2.2, color="#2166AC")
ax1.axvline(1.0, color="#2E8B57", ls="--", lw=1.5, label="Admissible boundary $w = 1$")
ax1.set_xlabel("Heuristic weight $w$")
ax1.set_ylabel("Expanded grid cells")
ax1.set_title("Expanded cells against the weight $w$")
ax1.legend(fontsize=8)
ax2.plot(weights_w[mask_ge1], weights_w[mask_ge1], lw=1.8, ls="--", color="#C0392B", label="Worst-case Pohl bound $w$")
ax2.plot(weights_w[mask_ge1], ratios_w[mask_ge1], marker="s", lw=2.3, color="#2E8B57", label="Empirical suboptimality $C(w)/C^*$")
ax2.set_xlabel(r"Heuristic weight $w \geq 1$")
ax2.set_ylabel("Cost ratio $C(w) / C^*$")
ax2.set_title("Cost ratio against Pohl's bound")
ax2.legend(fontsize=8)
label_panels(fig)
plt.show()
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 9.3. Weighted A* on the route of Demonstration 1. (a) Expanded cells against the weight ; the vertical line marks . (b) Cost ratio (solid) against Pohl’s bound (dashed): the actual loss is at most 20 % at , far below the bound.
What Demonstration 3 shows. the bound is far from tight here. At it guarantees , 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 plain requires orthogonal zig-zag steps instead of —a path too long. Enabling 8-neighbor diagonal moves (allow_diagonal=True, step length , paired with Euclidean heuristic ) reduces this bias: on the flat plain the 8-neighbour path has the exact length , and on the mountain terrain its cost, 93.72, is 12.7 % below the 4-neighbour cost, 107.35.
heading("Demonstration 4: 4-neighbor taxicab staircase bias against 8-neighbor diagonal routing")
# 1. Exact geometric check on a uniform flat plane (cost = 1.0 everywhere) from (0, 0) to (20, 20):
flat_grid = np.ones((25, 25), dtype=float)
flat_4 = greedy_heuristic_search.grid_shortest_path_search(flat_grid, (0, 0), (20, 20), method="astar", allow_diagonal=False)
flat_8 = greedy_heuristic_search.grid_shortest_path_search(flat_grid, (0, 0), (20, 20), method="astar", allow_diagonal=True)
assert np.isclose(flat_4["total_cost"], 40.0, atol=1e-12)
assert np.isclose(flat_8["total_cost"], 20.0 * math.sqrt(2.0), atol=1e-12)
# 2. Compare 4-neighbor vs. 8-neighbor optimal A* corridors on the mountain topography:
terr_4 = greedy_heuristic_search.grid_shortest_path_search(cost_grid, start_ab, goal_ab, method="astar", allow_diagonal=False)
terr_8 = greedy_heuristic_search.grid_shortest_path_search(cost_grid, start_ab, goal_ab, method="astar", allow_diagonal=True)
terr_8_dijk = greedy_heuristic_search.grid_shortest_path_search(cost_grid, start_ab, goal_ab, method="dijkstra", allow_diagonal=True)
assert np.isclose(terr_8["total_cost"], terr_8_dijk["total_cost"], atol=1e-12)
assert terr_8["total_cost"] < 0.95 * terr_4["total_cost"]
print(f"Flat 20x20 diagonal : 4-Neighbor = {flat_4['total_cost']:.3f} vs. 8-Neighbor = {flat_8['total_cost']:.3f} (exact 20*sqrt(2))")
print(f"Mountain (6,6)->(48,48): 4-Neighbor A* = {terr_4['total_cost']:.2f} vs. 8-Neighbor A* = {terr_8['total_cost']:.2f} (exact = {terr_8_dijk['total_cost']:.2f})")
p4 = np.array(terr_4["path"])
p8 = np.array(terr_8["path"])
fig, ax = plt.subplots(figsize=(7.0, 4.6))
ax.imshow(elev_m, origin="lower", cmap="terrain", alpha=0.88)
ax.plot(p4[:, 1], p4[:, 0], lw=2.1, ls="--", color="#F2C744", label=f"4-neighbor Manhattan A* (cost = {terr_4['total_cost']:.1f})")
ax.plot(p8[:, 1], p8[:, 0], lw=2.5, color="#19D3C5", label=f"8-neighbor Euclidean A* (cost = {terr_8['total_cost']:.1f})")
ax.set_xlabel("Column $c$")
ax.set_ylabel("Row $r$")
ax.set_title("4-neighbor staircase against 8-neighbor path")
ax.grid(False)
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.17), ncol=1, fontsize=8.5)
plt.show()
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 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 (), the search region of Dijkstra can be reduced by searching from both ends. Two disks of radius around start and goal have combined area —half the area of one disk of radius .
Two details matter in bidirectional Dijkstra on our cell-entry cost grid ():
Forward search relaxes outgoing edges with weight ; backward search from
goalrelaxes incoming forward edges (stepping backward from to adds ), so at any meeting cell , equals the exact path cost with zero double-counting of .Search terminates only when , where is the best complete path cost seen across any touched pair. We inspect
grid_shortest_path_searchand verifybidirectional_dijkstra_grid.
Check against the library¶
heading("Inside the algorithm: grid_shortest_path_search and exact bidirectional Dijkstra")
print(show_source(greedy_heuristic_search.grid_shortest_path_search))
import heapq
def bidirectional_dijkstra_grid(
cost_grid: np.ndarray,
start: tuple[int, int],
goal: tuple[int, int],
) -> dict:
"""Exact 4-neighbor Bidirectional Dijkstra matching grid_shortest_path_search cell-entry costs."""
h, w = cost_grid.shape
sr, sc = start
gr, gc = goal
if (sr, sc) == (gr, gc):
return {"total_cost": 0.0, "nodes_expanded": 1}
moves = [(-1, 0), (1, 0), (0, -1), (0, 1)]
gf = np.full((h, w), math.inf)
gb = np.full((h, w), math.inf)
closed_f = np.zeros((h, w), dtype=bool)
closed_b = np.zeros((h, w), dtype=bool)
gf[sr, sc] = 0.0
gb[gr, gc] = 0.0
pq_f: list[tuple[float, int, int]] = [(0.0, sr, sc)]
pq_b: list[tuple[float, int, int]] = [(0.0, gr, gc)]
best_mu = math.inf
expanded = 0
while pq_f and pq_b:
if pq_f[0][0] + pq_b[0][0] >= best_mu - 1e-13:
break
# Alternate expanding whichever frontier currently has the smaller top key:
if pq_f[0][0] <= pq_b[0][0]:
df, r, c = heapq.heappop(pq_f)
if closed_f[r, c]:
continue
closed_f[r, c] = True
expanded += 1
if closed_b[r, c]:
best_mu = min(best_mu, df + gb[r, c])
for dr, dc in moves:
nr, nc = r + dr, c + dc
if 0 <= nr < h and 0 <= nc < w and math.isfinite(cost_grid[nr, nc]):
nd = df + float(cost_grid[nr, nc])
if nd < gf[nr, nc] - 1e-13:
gf[nr, nc] = nd
heapq.heappush(pq_f, (nd, nr, nc))
if math.isfinite(gb[nr, nc]):
best_mu = min(best_mu, nd + gb[nr, nc])
else:
db, r, c = heapq.heappop(pq_b)
if closed_b[r, c]:
continue
closed_b[r, c] = True
expanded += 1
if closed_f[r, c]:
best_mu = min(best_mu, gf[r, c] + db)
# Stepping backward from (r, c) to predecessor (pr, pc) traverses forward edge (pr, pc) -> (r, c) of cost grid[r, c]
w_edge = float(cost_grid[r, c])
for dr, dc in moves:
pr, pc = r + dr, c + dc
if 0 <= pr < h and 0 <= pc < w and math.isfinite(cost_grid[pr, pc]):
nd = db + w_edge
if nd < gb[pr, pc] - 1e-13:
gb[pr, pc] = nd
heapq.heappush(pq_b, (nd, pr, pc))
if math.isfinite(gf[pr, pc]):
best_mu = min(best_mu, gf[pr, pc] + nd)
return {"total_cost": float(best_mu), "nodes_expanded": expanded}
for s_pt, g_pt in [((10, 10), (22, 22)), ((14, 14), (24, 24)), ((36, 36), (48, 48))]:
uni = greedy_heuristic_search.grid_shortest_path_search(cost_grid, s_pt, g_pt, method="dijkstra")
bi = bidirectional_dijkstra_grid(cost_grid, s_pt, g_pt)
assert np.isclose(bi["total_cost"], uni["total_cost"], atol=1e-12)
assert bi["nodes_expanded"] < uni["nodes_expanded"]
print(f"Route {s_pt} -> {g_pt}: Cost = {bi['total_cost']:.6f} (exact match) | Uni-Dijkstra = {uni['nodes_expanded']} vs. Bi-Dijkstra = {bi['nodes_expanded']} nodes")
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.
Verify a result. Across every directed 4-neighbor and 8-neighbor edge of
make_topographic_terrain(56, 56, seed=42), verify heuristic consistency and , and verify that is monotonically non-decreasing along admissible 's expansion order.Find how it fails. Verify
ValueErrorguards ongrid_shortest_path_search, then demonstrate quantitatively (a) how replacing with or in breaks admissibility and returns a suboptimal path, and (b) how pairing a Manhattan heuristic with 8-neighbor diagonal moves returns a strictly suboptimal route.Implement it yourself. Implement
multi_waypoint_terrain_planner(cost_grid, depot, waypoints)combining pairwise 8-neighbor admissible shortest paths with exact Held–Karp subset DP () to route an autonomous rover fromdepotthrough geological targets and back todepot. Verify exact cost agreement against all permutations and compare against greedy Nearest-Neighbor.
heading("Self-check for the exercises")
assert res_dijk["total_cost"] < 0.80 * res_bfs["total_cost"]
assert np.isclose(astar_pass["total_cost"], dijk_pass["total_cost"], atol=1e-12) and exp_ratio < 1.0 / 3.0
assert np.all(ratios_w[mask_ge1] <= weights_w[mask_ge1] + 1e-12)
assert np.isclose(bidirectional_dijkstra_grid(cost_grid, start_ab, goal_ab)["total_cost"], res_dijk["total_cost"], atol=1e-12)
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.