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
INPUTALGORITHMRESULT0201S02GStart: (0,1)Goal: (3,1)0 = walkable (cost 1)1 = obstacle (blocked)2 = rough terrain (cost 5)1Initialize: f=g+h2Pop lowest f-score3Add neighbors to queue4Repeat until goal foundManhattan Distance:h(n) = |x1-x2| + |y1-y2|Guides search toward goalOptimal Path FoundCost: 6Length: 4 stepsExplored: 4 cellsPath: (0,1) → (1,1) → (2,1) → (3,1)Costs: 1 + 1 + 5 + 1 = 8A* explores minimal cellswhile guaranteeing optimalityKey Insight:A* combines actual path cost with Manhattan distance heuristic to efficiently find optimal paths while exploring minimal cells.TutorialsPoint - A* Pathfinding Algorithm | Heuristic Search
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28 Meta 25
23.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen