← L&T Mindtree bank

L&T Mindtree · Question 62

Shortest Path in Binary Matrix

Javacode⏱ O(n²)💾 O(n²)
Service-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.

Sample input / output

Input:
grid = [[0, 1], [1, 0]]
Output:
2

Constraints

n x n grid; 1 <= n <= 100.

Solution — read it, then walk it

Time O(n²)Space O(n²)Loops 3Branches 3Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyes↻ repeat↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static intshortestPathBinaryMatrix(int[][]grid)if (grid[0][0] == 1)return -1DEFINE n = grid.lengthDEFINE [][] dirs ={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}}Queue<int[]> q = newLinkedList<>()q.offer(new int[]{0, 0})grid[0][0] = 1DEFINE steps = 1while (!q.isEmpty())DEFINE size = q.size()for (int i = 0; i <size; i++)DEFINE [] cell = q.poll()if (cell[0] == n - 1&& cell[1] == n - 1)return stepsfor (int[] d : dirs)DEFINE nr = cell[0] + d[0],nc = cell[1] + d[1]if (nr >= 0 && nr < n&& nc >= 0 && nc < n&& grid[nr][nc] == 0)grid[nr][nc] = 1q.offer(new int[]{nr, nc})steps++RETURN -1DEFINE static voidmain(String[] args)DEFINE [][] grid = {{0, 1},{1, 0}}System.out.println(shortestPathBinaryMatrix(grid))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/26

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