P11 · 2 seconds · 256 MB

Grid Shortest Path

You are given a grid of `0` (open) and `1` (wall). Start at the top-left cell `(0, 0)` and walk to the bottom-right cell `(h-1, w-1)`. You may move up, down, left, or right into an open cell (not diagonally). Return the minimum number of steps, or `-1` if there is no path. If start equals the end, the answer is `0`. If start or end is a wall, return `-1`.

function shortestPath(grid) → number

CONSTRAINTS

  • 1 ≤ h, w ≤ 50 in this arena (the pattern scales to 1000+)
  • grid[r][c] is 0 or 1
Input: grid = [ [0, 0, 0], [1, 1, 0], [0, 0, 0] ]
Output: 4
(0,0)→(0,1)→(0,2)→(1,2)→(2,2) is 4 steps. Going around the walls is longer.
Input: grid = [ [0, 1], [1, 0] ]
Output: -1
Input: grid = [[0]]
Output: 0
1
2
3
4
5
6
7
8

Arena judges JavaScript in a Web Worker (1s wall-clock, then TLE). Samples are public; submit runs hidden tests too. C++/Python is a later swarm package.