← Google bank

Google · Question 51 · Queues

Shortest Path in Binary Matrix

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

Problem

Find the shortest clear path from top-left to bottom-right in a binary matrix moving in 8 directions.

Approach

Use BFS to find the shortest path length.

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

How it works

  1. 1Check that start and end cells are clear.
  2. 2Use BFS with distance tracking.
  3. 3Visit neighbours in 8 directions if unblocked.
  4. 4Return the distance when the destination is reached.

Sample input / output

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

Constraints

n == grid.length == grid[i].length; 1 <= n <= 100; cells are 0 or 1.

Solution — read it, then walk it

Time O(n²)Space O(n²)Loops 2Branches 4Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesno↻ repeatyes↻ repeat↻ repeatyesnoSTARTfrom collections importdequeDEFINEshortestPathBinaryMatrix(grid)n = len(grid)if grid[0][0] orgrid[n - 1][n - 1]RETURN -1directions = [(-1, -1),(-1, 0), (-1, 1), (0, -1),(0, 1), (1, -1), (1, 0)…queue = deque([(0, 0, 1)])visited = {(0, 0)}while queuer, c, dist =queue.popleft()if r == c == n - 1RETURN distfor dr, dc indirectionsnr, nc = r + dr, c + dcif 0 <= nr < n and 0<= nc < n andgrid[nr][nc] == 0 an…visited.add((nr, nc))queue.append((nr, nc, dist+ 1))RETURN -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/28

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