Compute Nearest Destination Distances
DoorDashSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to use Multi-Source Breadth-First Search (BFS) to find the distance from every empty cell to the nearest destination in a grid.
Problem Statement
You are given a 2D grid of size m x n consisting of three types of cells:
0: An empty space that you can move through.1: An obstacle that you cannot enter.2: A destination.
Your task is to return a grid of the same dimensions where each cell contains the shortest distance from that cell to the nearest destination. If a cell is an obstacle, mark it as -1. If an empty cell is unreachable from any destination, mark it as -1.
You can move up, down, left, or right. Each move has a cost of 1.
Function Signature
def nearest_destination(grid: List[List[int]]) -> List[List[int]]:
Examples
Example 1:
Input: grid = [[0, 0, 0], [0, 1, 0], [0, 0, 2]]
Output: [[4, 3, 2], [3, -1, 1], [2, 1, 0]]
Example 2:
Input: grid = [[2, 0], [1, 1]]
Output: [[0, 1], [-1, -1]]
Constraints
m == grid.lengthn == grid[0].length1 <= m, n <= 500grid[i][j]is either0,1, or2.
Hints
Hint 1
Instead of running a BFS from every single cell to find the nearest destination, consider reversing the perspective.
Hint 2
Initialize a queue with the coordinates of all destination cells ('2') and set their initial distance to 0.
Hint 3
Perform a multi-source BFS, propagating the distance to all adjacent empty cells ('0') while skipping obstacles.
Follow-up questions
- What is the time and space complexity of your solution in terms of grid dimensions M and N?
- How would you modify your algorithm if certain destinations were 'faster' to reach than others (i.e., different edge weights)?
- What if the grid is so large that it does not fit in memory? How would you approach the problem?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.