Nearest Bathroom for Every Desk
An office floor is a grid of characters: B is a bathroom, D a desk, _ open floor and # a wall. From any cell you can step up, down, left or right into any cell that is not a wall; desks and bathrooms are walkable.
Return a grid of the same shape holding, for every desk, the number of steps to its nearest bathroom, or -1 if no bathroom is reachable. Every cell that is not a desk is -1.
desksToBathrooms(["B_D",
"_#_",
"D_B"])
-> [[-1, -1, 2],
[-1, -1, -1],
[ 2, -1, -1]]Hints
Hint 1
Start the BFS from every bathroom at once, all at distance 0. The first time the wave reaches a cell is its shortest distance, so each cell is labelled once.
Hint 2
Use the distance grid itself as the visited set (-1 means unvisited) and skip walls; at the end, blank out every cell that is not a desk.