A* Pathfinding

exact_matchHardby cg
graphsearchingoptimization

Solutions

0

Completed

0

Best Score

--

Last 24h

0

Description

Find the shortest path on a 2D grid using the A* algorithm with Manhattan distance heuristic. The grid contains 0s (passable) and 1s (walls). Movement is 4-directional (up, down, left, right), and each step costs 1. Return the path as a list of [row, col] coordinates from start to end (inclusive), and the total cost. If no path exists, return an empty path with cost -1. When multiple paths have the same f-score, break ties by preferring lower g-score, then by exploring neighbors in order: up, down, left, right.

Input Specification

A JSON object with keys:
  "grid": 2D array of 0s and 1s (0=passable, 1=wall)
  "start": [row, col] — starting position
  "end": [row, col] — ending position

Example: {"grid": [[0,1,0],[0,0,0]], "start": [0,0], "end": [1,2]}

Output Specification

A JSON object with keys:
  "path": array of [row, col] — coordinates from start to end
  "cost": integer — total path cost, or -1 if no path exists

Example: {"path": [[0,0],[1,0],[1,1],[1,2]], "cost": 3}

Example Test Cases

Test Case 1

Input

{
  "end": [3, 3],
  "grid": [
    [0, 0, 0, 0],
    [0, 1, 1, 0],
    [0, 0, 0, 0],
    [0, 1, 0, 0]
  ],
  "start": [0, 0]
}

Expected Output

{
  "cost": 6,
  "path": [
    [0, 0],
    [0, 1],
    [0, 2],
    [0, 3],
    [1, 3],
    [2, 3],
    [3, 3]
  ]
}

Test Case 2

Input

{ "end": [0, 4], "grid": [
  [0, 0, 0, 0, 0]
], "start": [0, 0] }

Expected Output

{ "cost": 4, "path": [
  [0, 0],
  [0, 1],
  [0, 2],
  [0, 3],
  [0, 4]
] }

Submit a Solution

Your code must define a solve(input) function. It will be sandboxed and benchmarked against all test cases (including hidden ones).

Python4 lines · 52 chars

Leaderboard

No solutions on the leaderboard yet.