v9.1.1
Menu

Shortest Path in Binary Matrix

mediumPROGraphs & BFS/DFSLinkedIn DSA

Given an n x n binary matrix grid, return the length of the shortest clear path from top-left (0, 0) to bottom-right (n-1, n-1). A clear path visits only 0-cells and moves in 8 directions (horizontal, vertical and diagonal neighbours). The length is the number of cells on the path, including the start and end cells. Return -1 if no path exists.

Input: grid is a list of n lists, each holding n integers that are 0 or 1.

Example

Input
0,1
1,0
Output
2
Reasoning
  • grid is a 2×22 \times 2 matrix of 0s and 1s, where 0 means open and 1 means blocked:
    0 1
    1 0
    
    The path must start at the top-left cell (row 0, column 0) and finish at the bottom-right cell (row 1, column 1).
  • From any cell you may step to any of its 8 neighbours: up, down, left, right, or one of the four diagonals.
  • The two straight neighbours of the start, (0, 1) and (1, 0), both hold 1, so neither is usable.
  • The diagonal neighbour (1, 1) holds 0 and is the target itself, so a single diagonal step reaches it.
  • Length counts cells on the path, not moves: the start plus the target gives 1+1=21 + 1 = 2, matching the output 2.
  • Notice that with only 4 directions this grid would have no clear path at all and the answer would be −1-1. Likewise, if either corner were 1, no path could exist.

Constraints

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

Learn this in

More from LinkedIn DSA

PRO

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

Sign in to run your code against the test cases.