A* Pathfinding on a Grid
The pathfinder inside games and robots: A* finds the shortest route on a grid by expanding nodes in order of "cost so far + estimated cost to go". The heuristic focuses the search toward the goal instead of spreading out blindly like plain BFS. Return the shortest path length. Solve it in Python or TypeScript, with hidden tests.
The problem
Given a grid of 0 (open) and 1 (wall), a start cell and a goal cell (both [row, col]), return the length (number of steps) of the shortest path using 4-directional moves, or -1 if the goal is unreachable. Use A* with the Manhattan-distance heuristic.
grid = [[0,0,0],[1,1,0],[0,0,0]], start = [0,0], goal = [2,0]6grid = [[0,1],[1,0]], start = [0,0], goal = [1,1]-1- Moves are up/down/left/right only (no diagonals); each step costs 1.
- The Manhattan distance
|dr| + |dc|is an admissible heuristic (never overestimates), so A* returns the true shortest length. - Expand nodes in order of
f = g + h(cost-so-far + heuristic); returngat the goal, or-1if the frontier empties first.
Your turn — write it
Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.
Implement astar(grid, start, goal): keep a frontier of cells ordered by f = g + h, and the best g reached per cell. Pop the lowest-f cell; if it is the goal return its g; otherwise relax its open neighbours. Return -1 if the frontier empties.
gis the number of steps taken to reach a cell;his the Manhattan distance from that cell to the goal.- Order the frontier by
f = g + h. A priority queue is ideal; for small grids, scanning the frontier for the minimum works too. - Track the best
gfound for each cell; only push a neighbour when you reach it with a smallerg. - Because the heuristic never overestimates, the first time you pop the goal, its
gis the shortest path length.
Explore the topic
See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.