A* Pathfinding - Problem
Implement the A* (A-star) pathfinding algorithm on a weighted grid to find the shortest path from a start position to a goal position.
The grid contains:
• 0 - walkable cells with cost 1
• 1 - obstacles (impassable)
• 2 - high-cost terrain with cost 5
Use Manhattan distance as the heuristic function: |x1 - x2| + |y1 - y2|
Return an array containing:
1. The minimum cost to reach the goal
2. The path as coordinates [x, y] from start to goal
3. All explored coordinates during the search
If no path exists, return [-1, [], []]
Input & Output
Example 1 — Basic Pathfinding
$
Input:
grid = [[0,2,0,1],[0,0,2,0]], start = [0,1], goal = [3,1]
›
Output:
[6,[[0,1],[1,1],[2,1],[3,1]],[[0,1],[1,1],[2,1],[3,1]]]
💡 Note:
Path from (0,1) to (3,1): cost 1+1+5+1 = 6 (high-cost terrain at (2,1) costs 5). A* finds optimal path efficiently.
Example 2 — Obstacle Avoidance
$
Input:
grid = [[0,1,0],[0,1,0],[0,0,0]], start = [0,0], goal = [2,0]
›
Output:
[4,[[0,0],[0,1],[0,2],[1,2],[2,2],[2,1],[2,0]],[[0,0],[0,1],[0,2],[1,2],[2,2],[2,1],[2,0]]]
💡 Note:
Must go around obstacle column. Path: down, right, up. Total cost: 6 moves × 1 = 6.
Example 3 — No Path Available
$
Input:
grid = [[0,1],[1,0]], start = [0,0], goal = [1,1]
›
Output:
[-1,[],[[0,0]]]
💡 Note:
Start and goal are separated by obstacles. No valid path exists, return -1 with explored cells.
Constraints
- 1 ≤ grid.length ≤ 100
- 1 ≤ grid[0].length ≤ 100
- grid[i][j] ∈ {0, 1, 2}
- 0 ≤ start[0], goal[0] < grid[0].length
- 0 ≤ start[1], goal[1] < grid.length
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code