FREE PYTHON TUTORIAL · NO ACCOUNT NEEDED
Robot path planning in Python: a working BFS example
Write a planner that finds a route around walls. This guide includes complete Python code, checks you can run, and an explanation of when to use BFS, Dijkstra or A*.
By AptRobo · Updated
1. Turn the room into a grid
Our robot starts at (0, 2) and must reach (4, 2) on a 5 × 5 grid. The first number is the column, the second is the row. Coordinates start at zero in the top-left corner.
..... ..#.. S.#.G ..#.. .....
S is the start, G is the goal and # is a wall. The robot can move one cell right, up, down or left. It cannot move diagonally or enter a wall. Every legal move costs one step.
The direct four-step route is blocked. A shortest legal detour needs eight moves: go around the top or bottom of the wall, then return to the goal's row. This is a simplified map model, not software for controlling a real robot.
2. Run a complete BFS path planner in Python
Save the following code as robot_path_planning.py, or download the free Python example. Run python robot_path_planning.py in a terminal. On systems where Python 3 uses a separate command, run python3 robot_path_planning.py. No packages need installing.
from collections import deque
def shortest_path(width, height, walls, start, goal):
"""Find a fewest-move path on a four-direction, equal-cost grid."""
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 start in walls or goal in walls:
return []
frontier = deque([start])
parent = {start: None}
while frontier:
cell = frontier.popleft()
if cell == goal:
path = []
while cell is not None:
path.append(cell)
cell = parent[cell]
return path[::-1]
x, y = cell
for dx, dy in [(1, 0), (0, -1), (0, 1), (-1, 0)]:
neighbour = (x + dx, y + dy)
if inside(neighbour) and neighbour not in walls and neighbour not in parent:
parent[neighbour] = cell
frontier.append(neighbour)
return []
if __name__ == "__main__":
walls = {(2, 1), (2, 2), (2, 3)}
path = shortest_path(5, 5, walls, (0, 2), (4, 2))
assert len(path) - 1 == 8
assert path[0] == (0, 2) and path[-1] == (4, 2)
assert all(cell not in walls for cell in path)
assert all(abs(a[0] - b[0]) + abs(a[1] - b[1]) == 1
for a, b in zip(path, path[1:]))
assert shortest_path(3, 3, {(1, 0), (1, 1), (1, 2)}, (0, 1), (2, 1)) == []
assert shortest_path(1, 1, set(), (0, 0), (0, 0)) == [(0, 0)]
assert shortest_path(2, 2, {(1, 1)}, (0, 0), (1, 1)) == []
print("Moves:", len(path) - 1)
print("Path:", path)
print("All checks passed")
Expected output
Moves: 8
Path: [(0, 2), (1, 2), (1, 1), (1, 0), (2, 0), (3, 0), (4, 0), (4, 1), (4, 2)]
All checks passedThe neighbour order makes this example choose the upper detour. Another order can produce a different route with the same eight moves. The checks verify the route's length, endpoints, legal steps, wall avoidance, an unreachable goal, a blocked goal and the start-equals-goal case.
If python is not found, install Python 3 from the official Python website. If a check fails, first compare your map dimensions, wall coordinates and move rules with the example.
3. Why breadth-first search finds a shortest route
The frontier is a first-in, first-out queue. We put the start in first. Each time we remove a cell, we add its unvisited free neighbours at the back. This explores cells one move away before cells two moves away, then three, and so on.
The parent dictionary serves two purposes: it records visited cells, preventing repeated exploration, and remembers which cell first discovered each neighbour. Once the goal is removed from the queue, following these parents back to the start reconstructs the route. Reversing that list puts it in travel order.
If the queue becomes empty before reaching the goal, the function returns an empty list. That means there is no route within this particular grid and its move rules. It does not mean no route exists in the physical world.
For a grid with width × height cells and at most four edges per cell, time and memory are both O(width × height) in the worst case. Breadth-first search gives a fewest-move route here because every move has the same cost.
Try three changes
- Remove all walls. The route now needs four moves. Update the eight-move check to four.
- Replace the wall with
{(2, y) for y in range(5)}. It separates the start from the goal; the result is empty. Replace the example's route assertions with a check for[]. - Move the start onto the goal. The route contains one cell and requires zero moves.
Prefer experimenting before coding? Try the free interactive robot-route lesson, then compare shortest routes in lesson two.
4. BFS vs Dijkstra vs A*: which planner should you use?
For weighted terrain, follow the complete Dijkstra Python tutorial with runnable code and compare a four-move expensive route with a six-move cheap detour.
| Planner | Suitable problem | Important condition |
|---|---|---|
| BFS | Find the fewest moves on an equal-cost grid. | Every move has the same cost. |
| Dijkstra | Find the lowest total movement cost, such as avoiding expensive rough floor. | Edge costs are non-negative; expand the cheapest accumulated cost first. |
| A* | Find a lowest-cost route while using an estimate of the distance still to go. | The heuristic and implementation must preserve optimality; do not assume any estimate is safe. |
BFS does not become a weighted planner merely by adding floor prices to the map. Dijkstra needs a priority queue and cost relaxation. A* adds a heuristic to the accumulated cost. On a four-direction grid with unit-cost moves, Manhattan distance is an admissible and consistent heuristic. Diagonal moves or other cost rules require reconsidering that choice.
Run the free BFS and Dijkstra comparison to see a short expensive route compete with a longer cheap route. This tutorial implements BFS only; the comparison preview runs separately in your browser.
5. Turn the example into your own project
Follow our three Python robotics project briefs for concrete extensions, weighted-map test cases and a project report checklist.
Add a map loader, report unreachable goals clearly, test more obstacle layouts and compare the number of explored cells. If you implement weighted movement, add tests that distinguish the fewest moves from the lowest cost. Explain your own design decisions rather than submitting an unexplained copied script.
Our robot-navigation Python project preview shows a proposed guided pack with exercises, automated tests, reference solutions, maps and a report template. The proposed one-time price is ₹1,499. It is not on sale yet, has no confirmed launch date and collects no payment.
Preview the proposed project packThis tutorial and its example are free whether or not you express interest in the pack. No hardware, personal tutoring, certificate or job placement is included.
Further reading
For another explanation of graph search, read Red Blob Games' interactive introduction to A*. For the queue used here, see the Python deque documentation.