← Capgemini bank

Capgemini · Question 62

Shortest Path in Binary Matrix

C++code⏱ 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.
  3. 3First arrival at the corner is the shortest path.

Sample input / output

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

Constraints

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

Solution — read it, then walk it

Time O(n²)Space O(n²)Loops 3Branches 3Returns 2source · C++
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyes↻ repeat↻ repeat↻ repeatSTARTinclude <iostream>include <vector>include <queue>using namespace stdDEFINEshortestPathBinaryMatrix(vector<vector<int>>&grid)if (grid[0][0] == 1)return -1DEFINE n = grid.size()vector<vector<int>> dirs ={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}}queue<pair<int,int>> qq.push({0, 0})grid[0][0] = 1DEFINE steps = 1while (!q.empty())DEFINE size = q.size()for (int i = 0; i <size; i++)auto [x, y] = q.front()q.pop()if (x == n - 1 && y ==n - 1) return stepsfor (auto& dir : dirs)DEFINE nx = x + dir[0], ny= y + dir[1]if (nx >= 0 && nx < n&& ny >= 0 && ny < n&& grid[nx][ny] == 0)grid[nx][ny] = 1q.push({nx, ny})steps++RETURN -1DEFINE main()vector<vector<int>> grid ={{0, 0, 0}, {1, 1, 0}, {1,1, 0}}cout <<shortestPathBinaryMatrix(grid)<< endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/30

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