Funcia
Lv.2bfsgraphgridshortest-path

Shortest Path in 8 Directions

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
0

A cleaning robot crosses an H×WH \times W room grid, where 0 is a free cell and 1 is blocked by furniture.

The robot starts at the top-left cell (0, 0) and must reach the bottom-right cell (H-1, W-1). Each move goes to a free neighbouring cell in any of the 8 directions (including diagonals); a diagonal move is allowed even if both side cells are blocked.

Return the minimum number of cells on the path, including the start and the end, or -1 if the end cannot be reached or the start or end cell is blocked.

Examples

gridresult
[[0, 1], [1, 0]]2
[[0, 0, 0], [1, 1, 0], [1, 1, 0]]4
[[1, 0, 0], [1, 1, 0], [1, 1, 0]]-1

Example 1 — One diagonal move: cells (0,0) and (1,1).

Example 2 — (0,0) → (0,1) → (1,2) → (2,2) visits 4 cells.

Example 3 — The start cell is blocked.

Efficiency

This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.

Function signature

solution(grid: int[][]) → int

Constraints

  • 1≤H=1 \le H = grid.length ≤500\le 500
  • 1≤W=1 \le W = grid[i].length ≤500\le 500; all rows have the same length.
  • grid[i][j] is 0 or 1.

Expected complexity

Time
O(HW)
Space
O(HW)

Examples

gridExpected
[[0,1],[1,0]]2
[[0,0,0],[1,1,0],[1,1,0]]4
[[1,0,0],[1,1,0],[1,1,0]]-1

Hint

Hint

Every move costs 1, so a BFS from (0, 0) over the 8 neighbour directions gives the answer. Return -1 immediately if the start or end is blocked, and mark cells visited when you enqueue them. Re-sweeping the whole grid until no distance changes needs as many sweeps as the path is long on a winding maze, which times out.

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)200 msestimated
C++ (GCC, gnu++23)200 msderived
Python 3.131000 msderived
Java 251114 msderived
Kotlin 2.4 (JVM)1400 msestimated
C# 14 (.NET 10)1400 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness4013verdict only
performance605verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.