← DiffPush

Shortest Path in a Binary Matrix (8-Directional)

Standard Bar Graphs · Shortest Path Problems O(n^2) · O(n^2)

The Corner-to-Clearance Robot Run

A warehouse robot must travel from the north-west corner to the south-east corner of a floor grid. Blocked bays are marked 1 and open bays 0, and the robot may roll in any of the eight directions — including diagonals — across open bays only. The route planner wants the shortest run measured in bays entered, or confirmation that no diagonal-capable route exists.

Input: An n x n binary matrix grid where 0 is open and 1 is blocked.

Output: Return the number of cells on the shortest clear path from (0,0) to (n-1,n-1), or -1 if no such path exists.

Constraints

Examples

Example 1

Input: {"grid":[[0,1],[1,0]]}
Output: 2
The diagonal hop from corner to corner visits exactly two cells.

Example 2

Input: {"grid":[[0,0,0],[1,1,0],[1,1,0]]}
Output: 4
The only corridor hugs the top row and the right column: four bays.

Solve this in your browser →

Also on LeetCode ↗