Compute nearest gate distance in grid
Company: Robinhood
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates grid traversal, distance propagation, obstacle handling, and in-place matrix update competencies within the Coding & Algorithms domain. It is commonly asked in technical interviews to assess algorithmic problem-solving and traversal strategies under obstacle and complexity constraints, representing a practical application-level problem rather than purely conceptual theory.
Constraints
- 1 <= m, n <= 200
- Each grid value is one of {-1, 0, 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: Starting BFS from both gates fills each empty cell with the distance to the nearest gate.
Input: ([[0]],)
Expected Output: [[0]]
Explanation: A single gate already has distance 0.
Input: ([[2147483647, -1], [2147483647, 2147483647]],)
Expected Output: [[2147483647, -1], [2147483647, 2147483647]]
Explanation: There are no gates, so no empty cell can be updated.
Input: ([[0, 2147483647, 2147483647, 0, 2147483647]],)
Expected Output: [[0, 1, 1, 0, 1]]
Explanation: With multiple gates, each empty cell takes the distance to the closer gate.
Hints
- Running a separate BFS from every empty cell is too slow. Can you start from all gates at once instead?
- In an unweighted grid, the first time BFS reaches a cell is the shortest distance to that cell.