Fill rooms with nearest-gate distance
Company: Microsoft
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This Coding & Algorithms question evaluates algorithmic problem-solving with grid-based graph traversal and shortest-distance computation, assessing data-structure use and implementation-level efficiency for software engineers.
Constraints
- 0 <= m, n <= 250
- Each cell is one of: -1, 0, or 2147483647
- Movement is allowed only in 4 directions: up, down, left, right
Examples
Input: ([[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]],)
Expected Output: [[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]
Explanation: Distances are filled from both gates simultaneously. Each room gets the shortest path length to the nearest gate.
Input: ([[2147483647,-1,0],[2147483647,-1,2147483647],[2147483647,-1,2147483647]],)
Expected Output: [[2147483647,-1,0],[2147483647,-1,1],[2147483647,-1,2]]
Explanation: The middle column of walls blocks the left column completely, so those rooms remain 2147483647.
Input: ([],)
Expected Output: []
Explanation: An empty grid has nothing to update.
Input: ([[2147483647]],)
Expected Output: [[2147483647]]
Explanation: There is no gate, so the single empty room stays unchanged.
Hints
- Instead of running a search from every empty room, think about starting from every gate at the same time.
- A breadth-first search guarantees that the first time you reach a room, you found its shortest distance.