← Meta (Facebook) bank

Meta (Facebook) · Question 62

Shortest Path in Binary Matrix

Pythoncode⏱ O(n²)💾 O(n²)
Product-based

Problem

You are given n x n binary matrix. Find shortest clear path from top-left to bottom-right.

Approach

BFS layer by layer in 8 directions, marking visited by sinking cells.

Time O(n²)Space O(n²)

How it works

  1. 1Reject immediately if start or end is blocked.
  2. 2BFS expands one ring per step in 8 directions.
  3. 3First arrival at the corner is the shortest path.

Sample input / output

Input:
3
0 0 0
1 1 0
1 1 0
Output:
4

Constraints

n == grid.length; 1 <= n <= 100; cells 0/1.

Solution — read it, then walk it

Time O(n²)Space O(n²)Loops 3Branches 4Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesno↻ repeatyes↻ repeat↻ repeat↻ repeatyesnoSTARTfrom collections importdequeDEFINEshortestPathBinaryMatrix(grid)if grid[0][0] == 1RETURN -1n = len(grid)dirs = [[-1, -1], [-1, 0],[-1, 1], [0, -1], [0, 1],[1, -1], [1, 0], [1, 1]]q = deque([(0, 0)])grid[0][0] = 1steps = 1while qsize = len(q)for _ in range(size)x, y = q.popleft()if x == n - 1 and y ==n - 1RETURN stepsfor dx, dy in dirsnx, ny = x + dx, y + dyif 0 <= nx < n and 0<= ny < n andgrid[nx][ny] == 0grid[nx][ny] = 1q.append((nx, ny))steps += 1RETURN -1DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it))grid = [[int(next(it)) for_ in range(n)] for _ inrange(n)]print(shortestPathBinaryMatrix(grid))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/32

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits