PPractick

DSA interview question

Shortest Path in a Binary Matrix

Hard · Data structures · Topics: graph, bfs, matrix

The problem

A warehouse robot moves on an n × n floor grid where 0 is free and 1 is blocked. It starts at the top-left cell and must reach the bottom-right cell, moving to any of the 8 neighbouring cells (diagonals included). What's the shortest path length, counted as the number of cells visited including both ends, or −1 if there's no path? Every move costs the same, so BFS from the start gives the answer the first time it reaches the goal.

Example: [[0,0,0], [1,1,0], [1,1,0]] → 4.

Function signature

int shortestPathBinaryMatrix(const vector<vector<int>>& grid);  // n x n

Test cases

InputOutputExplanation
[[0,1],[1,0]]2One diagonal step
[[0,0,0],[1,1,0],[1,1,0]]4Right, diagonal, down
[[1,0,0],[1,1,0],[1,1,0]]-1The start is blocked
[[0,1],[1,1]]-1The goal is blocked
[[0]]1Start = goal

(Confirm: 8-directional moves; the path length counts cells, not moves; blocked start or goal gives −1.)

How interviewers phrase it

Clarifying questions to ask

  1. 4 or 8 directions? (8.)
  2. Is the length counted in cells or moves? (Cells.)
  3. What if the start or end is blocked? (−1.)

Follow-ups to expect

  1. "Why BFS and not Dijkstra?"
  2. "How are the 8 neighbours generated?"
  3. "Can you speed it up?"
  4. "What if moves had different costs?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in