Closest-Pair Dispatch of Couriers on a Walled Grid
Trees & GraphsAuto-graded · 21 test casesLast updated
Match couriers to parcels by repeatedly choosing the globally closest pair, using BFS shortest paths on a grid with walls and deterministic tie-breaking.
A warehouse floor is modeled as a rectangular grid with some cells walled off. There are k couriers and k parcels, and every courier must end up with exactly one parcel. Assignments are made greedily: the courier-parcel pair that is closest overall is matched first, then the closest pair among those still unmatched, and so on.
Implement a function that returns, for each courier, the index of the parcel it is given.
Input
grid: a 2D list of integers.grid[r][c] == 0means the cell is open andgrid[r][c] == 1means it is a wall.robots: a list ofkpositions[r, c].robots[i]is the starting cell of courieri.items: a list ofkpositions[r, c].items[j]is the cell of parcelj.
(The parameter names keep "robots" for couriers and "items" for parcels.)
Distance
A courier moves one step at a time to an adjacent cell (up, down, left or right). It cannot leave the grid or step onto a wall. The distance between courier i and parcel j is the fewest steps needed to get from the courier's cell to the parcel's cell. With no walls this is the Manhattan distance abs(r1 - r2) + abs(c1 - c2).
Assignment process
Work in rounds. In each round:
- Look at every pair made of an unassigned courier
iand an unassigned parcelj. - Choose the pair with the smallest distance.
- If several pairs share that smallest distance, choose the one with the smallest courier index
i. If still tied, choose the one with the smallest parcel indexj. - Assign parcel
jto courieri, and take both out of later rounds.
Continue until all couriers are assigned. Since the counts are equal, every parcel is used exactly once.
Output
Return a list result of length k where result[i] is the index of the parcel assigned to courier i.
Constraints
1 <= m, n <= 50, wherem = len(grid)andn = len(grid[0]); all rows have lengthn.- Each
grid[r][c]is0or1. 1 <= k <= 50andlen(robots) == len(items) == k.- Every position satisfies
0 <= r < mand0 <= c < n, and every courier and parcel is on an open cell. - Courier positions are pairwise distinct, and parcel positions are pairwise distinct. A courier and a parcel may share a cell (distance
0). - Every parcel is reachable from every courier, so all distances are defined.
Examples
Example 1
Input: assign_couriers([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0], [0, 3]], [[0, 2], [2, 0]])
Output: [1, 0]
Example 2
Input: assign_couriers([[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 1], [2, 1]], [[1, 1], [1, 0]])
Output: [0, 1]
Example 3
Input: assign_couriers([[0, 0, 0], [1, 1, 0], [0, 0, 0]], [[0, 0], [2, 2]], [[2, 0], [0, 2]])
Output: [1, 0]
Hints
Hint 1
Walls break Manhattan distance. Which standard algorithm gives exact shortest step counts on an unweighted grid, and how many times do you need to run it?
Hint 2
Once all k*k distances are known, each round picks the smallest (distance, courier index, parcel index) among free pairs. Think about what happens if you list all such triples in sorted order.
Hint 3
Scan the sorted triples once and accept a triple only if both its courier and its parcel are still unassigned. Prove by induction that this matches the round-by-round rule.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split the problem into two parts: computing distances, and doing the greedy matching.
Distances. Walls make Manhattan distance unreliable, so run a breadth-first search from each courier's start cell. BFS on an unweighted grid yields the true minimum step count to every cell. Each search only needs to record the distance when it reaches a parcel cell, and it can stop once all k parcels have been seen. This produces all k * k triples (distance, courier index, parcel index).
Matching. Each round selects the smallest (distance, courier, parcel) among pairs where both sides are still free. That is exactly the lexicographic order of the triples. So sort all triples once and scan them in order, accepting a triple only if its courier and its parcel are both still unassigned.
Why it is correct
- BFS dequeues cells in non-decreasing distance order, and a cell is marked when first enqueued, so the recorded distance is the minimum. Walls and out-of-grid cells are never enqueued, so paths respect obstacles.
- Induction on rounds: suppose the scan has made the same first
tassignments as the process. The pair chosen in roundt+1is the lexicographically smallest triple with both endpoints free. Every triple before it in sorted order must involve an already-assigned courier or parcel (otherwise it would have been chosen), so the scan skips them all, and then accepts the chosen pair. Hence the scan reproduces the process exactly. - Since there are
kcouriers,kparcels and every distance is defined, all couriers get assigned. - A courier standing on a parcel's cell finds it at distance
0when it dequeues its own start cell. Parcel positions are distinct, so a position-to-index map is well defined.
Complexity
- Time:
O(k * m * n)for the BFS runs plusO(k^2 log k)for sorting, with aO(k^2)scan. At the limits this is roughly 125,000 cell visits plus sorting 2,500 triples. - Space:
O(m * n)for one BFS distance grid at a time plusO(k^2)for the triples.
Reference solution
from collections import deque
from typing import List
def assign_couriers(grid: List[List[int]], robots: List[List[int]], items: List[List[int]]) -> List[int]:
m, n = len(grid), len(grid[0])
k = len(robots)
item_at = {}
for j, (r, c) in enumerate(items):
item_at[(r, c)] = j
triples = []
for i, (sr, sc) in enumerate(robots):
dist = [[-1] * n for _ in range(m)]
dist[sr][sc] = 0
q = deque([(sr, sc)])
found = 0
while q and found < k:
r, c = q.popleft()
j = item_at.get((r, c))
if j is not None:
triples.append((dist[r][c], i, j))
found += 1
d = dist[r][c] + 1
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] == 0 and dist[nr][nc] < 0:
dist[nr][nc] = d
q.append((nr, nc))
triples.sort()
result = [-1] * k
taken = [False] * k
for d, i, j in triples:
if result[i] < 0 and not taken[j]:
result[i] = j
taken[j] = True
return result