A small, dependency-free Python project that finds shortest paths through 2D grids and compares Breadth-First Search (BFS) with A*.
Requires Python 3.10 or newer. From this folder, run:
python main.pyThe program displays both searches on the same example grid, then benchmarks them on several grid sizes and obstacle densities. Random grids use fixed seeds so the benchmark cases can be reproduced.
Each grid is a list of lists. 0 is walkable and 1 is an obstacle. Positions use (row, column) coordinates; the start and goal are supplied separately.
The visualization uses S for the start, G for the goal, # for an obstacle, * for the final path, . for an explored cell, and 0 for an unexplored walkable cell. Start, goal, and obstacles take display priority over the path and explored markers.
Both algorithms move up, down, left, or right, and every move costs one. The path length printed by the program is the number of moves (edges), not the number of cells in the path. The explored count is the number of distinct cells removed from the search frontier and processed.
-
BFS uses a FIFO queue. It explores in increasing distance from the start, so it finds a shortest path on an unweighted grid. Its time and space complexity are
$O(V + E)$ , where$V$ is the number of walkable cells and$E$ is the number of neighbor connections. -
A* uses a min-heap ordered by
$g(n) + h(n)$ . Here,$g(n)$ is the known cost from the start, and$h(n)$ is Manhattan distance to the goal. The heuristic is admissible and consistent for four-directional, unit-cost movement, so A* returns a shortest path. With a binary heap its worst-case time is$O((V + E) \log V)$ and space is$O(V + E)$ .
Both functions return (path, explored). A path is a list of coordinates; if no path exists (or an endpoint is blocked or outside the grid), the path is None. The explored result is a set of coordinates. The benchmark checks that both algorithms agree on whether a path exists and on its length.
pathfinding.py: coordinate and grid helpers, including neighbor lookup and path reconstruction.algorithms.py: BFS, Manhattan distance, and A*.benchmarks.py: seeded grid generation and average performance measurements.main.py: example runs and console visualization.test_algorithms.py: focused correctness tests, runnable withpython -m unittest.
Benchmark timings are machine-dependent and should be treated as observations, not universal rankings. Each reported result averages three seeded grids for that size and obstacle density; path length averages only the trials where a path exists.