Ziqing Kerry Gao
← Writing

Building a Path-Finding Algorithm Visualizer

This project started with the Search lecture in Harvard’s CS50 Introduction to Artificial Intelligence with Python. I wanted to turn the abstract ideas of frontier expansion and heuristic-based search into something you could touch, and to compare the trade-offs between optimality, exploration cost, and heuristic guidance in real time.

You can try the live demo or read the code.

What it does

The visualizer runs Breadth-First Search, Depth-First Search, Greedy Best-First Search, and A* on a 2D grid, with bi-directional and heuristic settings. You can place obstacles, move the start and destination, change the playback speed, and run continuously or step by step. A live log tracks runtime, operations, visited nodes, and path length, so the theory has numbers next to it.

Keeping the UI smooth

The main design decision was to separate search from animation. The algorithm computes its result up front and records each state change in a steps array, and requestAnimationFrame replays those steps. Heavy computation on a large grid doesn’t turn into a stuttering animation.

State lives in Zustand with atomic updates, so only the grid cells being explored re-render, rather than the whole grid.

A* is implemented as an extensible AStarMaze class. It supports bi-directional search, which shrinks the search space by expanding from both the start and the goal, and four distance metrics for different movement constraints: Manhattan, Euclidean, Octile, and Chebyshev.

A* orders its frontier by f = g + h, and Greedy Best-First orders by f = h. The frontier is currently kept in order with Array.sort(). Replacing it with a true binary heap is the next optimization for high-density mazes.

Greedy Best-First vs. A*

Running both on the same maze makes the trade-off easy to see:

  • Optimality vs. greed. Greedy Best-First follows the local heuristic h(n). It reaches the target quickly but often takes a suboptimal, jagged route. A* balances that heuristic against the cost so far, g(n).
  • Search space. A* typically expands a larger frontier mid-search. Greedy Best-First explores less, at the expense of path quality.
  • Heuristics. Both algorithms use a heuristic, but only A* with an admissible heuristic guarantees the shortest path.