FREE PYTHON ROBOTICS TUTORIAL
Dijkstra path planning in Python: find a lower-cost robot route
A robot's shortest route can cross expensive terrain. Build a weighted grid planner that finds the lowest total cost, with runnable Python code and checks for obstacles, unreachable goals and invalid costs.
By AptRobo · Updated
Python 3.10+ · standard library only · basic dictionaries, tuples and loops · no hardware or account.
Get the runnable Dijkstra codeA weighted map: four moves cost 28, six moves cost 6
Use a five-column, three-row grid. Coordinates are (column, row), starting at zero. Start at (0, 1) and finish at (4, 1). The three middle cells of row 1 cost 9 to enter; every other cell costs 1.
1 1 1 1 1 S 9 9 9 G 1 1 1 1 1
The direct route has four moves and costs 9 + 9 + 9 + 1 = 28. A detour along the upper or lower row has six moves, each costing 1, for a total of 6. We pay when entering a cell, including the goal; the starting cell costs nothing.
BFS finds a fewest-move route on an equal-cost grid. It does not optimise these terrain prices. Dijkstra expands the cell with the lowest known accumulated cost instead. Costs must be non-negative.
Complete Dijkstra grid path planner in Python
Save this as dijkstra_path_planning.py or download the free Python example. Run python dijkstra_path_planning.py (or python3 dijkstra_path_planning.py). No packages need installing.
from heapq import heappop, heappush
from math import inf, isfinite
def cheapest_path(width, height, walls, costs, start, goal):
"""Four-direction grid; cost is paid when entering a cell."""
def inside(cell):
x, y = cell
return 0 <= x < width and 0 <= y < height
if width <= 0 or height <= 0:
raise ValueError("Grid dimensions must be positive")
if not inside(start) or not inside(goal):
raise ValueError("Start and goal must be inside the grid")
if any(not isfinite(c) or c < 0 for c in costs.values()):
raise ValueError("Costs must be finite and non-negative")
if start in walls or goal in walls:
return [], inf
best = {start: 0}
parent = {start: None}
frontier = [(0, start)]
while frontier:
total, cell = heappop(frontier)
if total != best[cell]:
continue # A cheaper entry superseded this one.
if cell == goal:
route = []
while cell is not None:
route.append(cell)
cell = parent[cell]
return route[::-1], total
x, y = cell
for nxt in ((x + 1, y), (x, y - 1), (x, y + 1), (x - 1, y)):
if not inside(nxt) or nxt in walls:
continue
candidate = total + costs.get(nxt, 1)
if candidate < best.get(nxt, inf):
best[nxt] = candidate
parent[nxt] = cell
heappush(frontier, (candidate, nxt))
return [], inf
def run_checks():
start, goal = (0, 1), (4, 1)
costs = {(1, 1): 9, (2, 1): 9, (3, 1): 9}
route, total = cheapest_path(5, 3, set(), costs, start, goal)
assert total == 6 and len(route) - 1 == 6
assert route[0] == start and route[-1] == goal
assert all(abs(a[0] - b[0]) + abs(a[1] - b[1]) == 1
for a, b in zip(route, route[1:]))
assert sum(costs.get(cell, 1) for cell in route[1:]) == total
walls = {(2, y) for y in range(3)}
assert cheapest_path(5, 3, walls, costs, start, goal) == ([], inf)
assert cheapest_path(5, 3, {goal}, costs, start, goal) == ([], inf)
assert cheapest_path(5, 3, set(), costs, start, start) == ([start], 0)
zero_cost = {(x, y): 0 for x in range(5) for y in range(3)}
assert cheapest_path(5, 3, set(), zero_cost, start, goal)[1] == 0
assert cheapest_path(5, 3, set(), {}, start, goal)[1] == 4
for bad in (-1, float("nan"), float("inf")):
try:
cheapest_path(5, 3, set(), {goal: bad}, start, goal)
except ValueError:
pass
else:
raise AssertionError("Invalid cost accepted")
print("Moves:", len(route) - 1)
print("Cost:", total)
print("Path:", route)
print("All checks passed")
if __name__ == "__main__":
run_checks()
Expected result
Moves: 6 Cost: 6 Path: [(0, 1), (0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (4, 1)] All checks passed
The heap breaks equal-cost ties using the coordinate tuple, so this example takes the upper detour. A different tie rule can produce another equally cheap route.
How Dijkstra uses a priority queue
bestrecords the cheapest cost found so far for each cell. The start begins at zero.heappopremoves the smallest accumulated cost from the frontier. A stale entry is skipped if a cheaper entry has already replaced it.- For each legal neighbour, add the cost of entering it. If this improves its best cost, record the new parent and push the improved entry.
- Stop when the goal is popped with its current best cost. Follow parents back to reconstruct the route.
The improvement check uses <, rather than <=. Equal-cost routes do not overwrite parents; this also avoids repeatedly adding zero-cost cycles. Returning when the goal is first discovered is not the stopping rule used here.
On this four-direction grid with V cells, there are at most four outgoing edges per cell. With a binary heap, worst-case time is O(V log V) and memory is O(V). General graph bounds depend on the number of edges; this statement is specific to our grid.
Test the route, not just the printed picture
The included checks verify the six-cost detour, endpoints, adjacent steps and recalculated route cost. They also cover a solid wall separating start and goal, a blocked goal, start equal to goal, zero-cost movement, uniform movement costs and rejection of negative, infinite or NaN costs.
Try adding (2, 0) to the wall set. A valid cheapest route can still use the lower row. Check that none of its cells are walls. Then block both complete detours and compare the resulting cost with the direct route.
Common mistakes
- Using a FIFO queue for weighted costs: a fewest-move route may be expensive.
- Marking a neighbour permanently visited on discovery: a cheaper route may be found later.
- Charging for the starting cell or forgetting the final goal cell: use one consistent cost convention.
- Allowing negative movement costs: Dijkstra's assumptions no longer hold.
- Treating an empty route as a zero-cost success: this implementation returns an empty list and infinity when no route exists.
The function expects integer grid coordinates and numeric cost values. It validates dimensions, endpoints and finite non-negative costs; it is a teaching example rather than a general input parser.
Build on your weighted navigation planner
Load terrain prices from a map file, compare cost against move count, and record explored cells. Follow our Python robotics project briefs to add multiple delivery stops and document your experiments.
Try the free BFS and Dijkstra browser preview. The proposed guided project pack is not on sale yet and collects no payment; this tutorial and download remain free.
This is a static point-robot grid model. It does not include sensing, localisation, robot size, motion control or moving obstacles. It is not ready to operate physical hardware.
References
Python's official heapq documentation explains the min-heap operations. For graph-search background, see Red Blob Games' introduction to pathfinding.