Distance From Every Grid Cell to the Nearest Dark Store

Last updated: November 29, 2026

Quick Overview

A city is a grid where 'S' marks a dark store, '#' a blocked cell, and '.' an open cell. Return a grid with each open cell's shortest walking distance to any dark store, or -1 if unreachable.

Flipkart
Coding & Algorithms
Software Engineer
Flipkart
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

0

0 solved


A city is a grid where 'S' marks a dark store, '#' a blocked cell, and '.' an open cell. Return a grid with each open cell's shortest walking distance to any dark store, or -1 if unreachable.

Framed around Flipkart Minutes quick commerce, where serviceability depends on how close a customer is to a dark store. The interviewer is checking whether you see multi source BFS instead of running one BFS per cell or per store.

What the Interviewer Expects
  • Identify multi source BFS seeded with all stores at distance 0
  • Explain why BFS gives shortest paths on an unweighted grid
  • Mark visited when enqueuing to avoid duplicates
  • Handle blocked cells and unreachable regions with -1
  • State O(R*C) time and space
Key Topics to Cover
multi-source BFS
grid traversal
shortest path
matrix
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you also return which store is nearest to each cell?
  • What if some roads take twice as long to cross?
  • How would you answer the query for millions of real addresses instead of a grid?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Grid up to 1000 x 1000, cells S, #, ..
  • Movement in 4 directions, each step costs 1.
  • Output distance grid; stores are 0, blocked and unreachable cells are -1....
High-Level Design

A BFS from each cell, or from each store, is O((R*C)^2) in the worst case. Instead, put every store in the queue at distance 0 at once. BFS expands in layers of equal distance, so the first time a...


Submit Your Answer
Markdown supported