Implement A* on a grid
Standard · Write code · about 25 min
A grid holds 0 for an open cell and 1 for a wall. Move one step up, down, left or right onto open cells, each step costing 1.
Return the fewest steps from start to goal (each given as [row, col]), or -1 if the goal cannot be reached. Use A* with the Manhattan distance as the heuristic.
Example 1
Input:
[[[0,0,0,0,0],[0,0,1,0,0],[0,0,1,0,0],[0,0,0,0,0]],[2,0],[1,4]]
Output:
7
Go up, over the wall along row 0, then down to T.
Example 2
Input:
[[[0,1],[1,0]],[0,0],[1,1]]
Output:
-1
Walls block both ways out of the start.
Constraints
- 1 ≤ rows, cols ≤ 100
- grid[r][c] is 0 or 1
- start and goal are inside the grid
Learn the idea first: A* search with heuristics, a visual lesson.
More A* search with heuristics problems
- Admissible heuristic Warm-up
- Compare expansions with Dijkstra Standard