Assign Robots to Their Nearest Available Items
Problem statement
You are given a rectangular grid, robot coordinates robots, and item coordinates items. A cell containing 0 is free; a cell containing 1 is blocked. Coordinates are zero-based row and column pairs.
For this exercise, process robots in input order and assign each robot its nearest available reachable item:
- A move travels one free cell up, down, left, or right and costs one step. Distance is the shortest valid path length.
- An item can be assigned at most once. Among equally near available items, choose the one with the smallest index in
items. - If no available item is reachable, assign
-1; that robot reserves no item. - Robots and assigned items do not block movement. Each robot makes its choice using the items left by earlier robots.
Return an integer array in robot input order containing the assigned item index or -1. This is a sequential nearest-item policy; do not minimize the total distance across all robots. An all-free grid is the basic task; blocked cells implement its obstacle follow-up.
Function
assignNearestItems(grid: int[][], robots: int[][], items: int[][]) → int[]Examples
Example 1
grid = [[0,0,0],[0,0,0]]robots = [[0,0],[1,0]]items = [[0,2],[1,1]]return = [0,1]Both items are two steps from the first robot, so item index 0 wins. The second robot receives item 1.
Example 2
grid = [[0,1,0],[0,1,0],[0,0,0]]robots = [[0,0],[2,0]]items = [[0,2],[2,1]]return = [1,0]The first robot reaches item 1 in three steps; the wall makes item 0 six steps away. The second robot receives the remaining item 0.
Example 3
grid = [[0,1,0]]robots = [[0,0],[0,2]]items = [[0,2],[0,0]]return = [1,0]Each robot receives the item already on its free cell, at distance zero.
Constraints
1 <= grid.length, grid[0].length <= 30; all rows have equal length.0 <= robots.length == items.length <= 100.- Every coordinate is in bounds and on a free cell.
- Coordinates are distinct within each coordinate array; a robot and an item may occupy the same cell.
- Every grid value is
0or1.