PPractick

DSA interview question

Distance of the Nearest Cell Having 1

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

The problem

A city grid marks hospitals with 1 and ordinary blocks with 0. For planning ambulance coverage, every block needs its distance to the nearest hospital, moving up, down, left or right. Running a BFS from every block is O((R·C)²). Reverse the viewpoint instead: start a single BFS from all hospitals at once (multi-source). The first time the BFS reaches a block is its distance to the nearest hospital.

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

Function signature

vector<vector<int>> nearest(const vector<vector<int>>& grid);  // at least one 1 exists

Test cases

InputOutputExplanation
[[0,1,1,0],[1,1,0,0],[0,0,1,1]][[1,0,0,1],[0,0,1,1],[1,1,0,0]]
[[1,0,1],[1,1,0],[1,0,0]][[0,1,0],[0,0,1],[0,1,2]]
[[0,0],[0,1]][[2,1],[1,0]]
[[1,0,0,0]][[0,1,2,3]]
[[1]][[0]]

(Confirm: distance is the number of 4-directional steps; the grid has at least one 1.)

How interviewers phrase it

Clarifying questions to ask

  1. 4-directional moves? (Yes.)
  2. Is there always at least one 1? (Yes.)
  3. Can cells be blocked? (No, all cells are passable.)

Follow-ups to expect

  1. "Why start from all 1s?"
  2. "Why can't DFS do this?"
  3. "Without obstacles, isn't it just the Manhattan distance?"
  4. "Where else is multi-source BFS used?"
  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