Compute Nearest Destination Distances
Company: DoorDash
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Technical Screen
Quick Answer: This question evaluates graph and grid traversal concepts, specifically multi-source shortest-path computation on a grid and handling special-cell constraints such as obstacles that cannot be used as intermediate steps.
Constraints
- 0 <= m, n <= 500
- grid[i][j] is one of 'D', 'X', or '.'
- All rows have the same length
- An O(m * n) solution is expected
Examples
Input: ([['.', '.', 'D'], ['X', '.', '.'], ['.', 'X', '.']],)
Expected Output: [[2, 1, 0], [3, 2, 1], [-1, 3, 2]]
Explanation: Normal cells use BFS without passing through obstacles. Cell (2,0) cannot reach any destination because both possible directions are blocked by 'X'. Each 'X' cell gets 1 plus the best reachable neighboring non-'X' distance.
Input: ([['D']],)
Expected Output: [[0]]
Explanation: A destination is already at distance 0 from itself.
Input: ([['.', 'X'], ['X', '.']],)
Expected Output: [[-1, -1], [-1, -1]]
Explanation: There is no destination anywhere in the grid, so every cell is unreachable.
Input: ([['D', 'X', '.']],)
Expected Output: [[0, 1, -1]]
Explanation: The obstacle cell can step directly to the destination in 1 move. The open cell on the far right cannot reach the destination because it would have to pass through the obstacle.
Input: ([['.', '.', 'X', 'D'], ['.', 'X', '.', '.'], ['D', '.', '.', 'X'], ['.', 'X', '.', '.']],)
Expected Output: [[2, 3, 1, 0], [1, 2, 2, 1], [0, 1, 2, 2], [1, 2, 3, 4]]
Explanation: Using multi-source BFS from both destinations gives shortest distances for all non-'X' cells. Each obstacle cell then takes 1 plus the minimum reachable distance of its adjacent non-obstacle neighbors.
Input: ([],)
Expected Output: []
Explanation: An empty grid produces an empty result.
Hints
- If several destinations exist, think about starting a BFS from all destination cells at the same time.
- Because 'X' cells cannot be used as intermediate cells, compute distances for normal cells first, then derive each obstacle cell's answer from its adjacent non-obstacle cells.