PIXELBANKv9.1.0
Menu

Shortest Path in Binary Matrix

Given an n x n binary matrix, return the length of the shortest clear path from top-left to bottom-right. A clear path visits only 0-cells and moves in 8 directions. Return -1 if no path.

Input: n rows of comma-separated 0/1.

Example:

Input:
0,1
1,0
Output:
2
Reasoning:
  • The input is a 2×22 \times 2 binary matrix:
    0,1
    1,0
    
  • We start at the top-left cell (0) and explore neighboring cells in 8 directions, finding a clear path to the bottom-right cell (0) in 2 steps: right and down are blocked, so we go right then down, or down then right, but since the direct path is blocked by a 1, we consider diagonal moves and find that moving diagonally is not an option here, instead we move in an L-shape.
  • The shortest clear path has a length of 22 since we move in an L-shape: right then down, or down then right, but due to the 1-cell, the path is not completely straight.
  • The final output is 22.

Constraints:

  • 1 <= n <= 100
  • grid[i][j] is 0 or 1
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.