← 返回 snowflake 的题目列表Nearest Bathroom Distance for Each Desk in a Grid
类型:online_judge
You are given an m x n grid of characters where:
'B' represents a Bathroom
'D' represents a Desk
'_' represents an empty cell (walkable)
You can move up/down/left/right by 1 cell per step, and each step costs distance 1. You may traverse any number of '_', 'D', and 'B' cells as long as you stay within bounds.
Compute, for each desk, the shortest distance to the nearest bathroom. Return an integer matrix dist of the same size such that:
If grid[i][j] == 'D', then dist[i][j] is the shortest path length from (i,j) to any 'B'.
Otherwise, dist[i][j] = -1.
If a desk cannot reach any bathroom, its distance is -1.
Constraints
1 <= m, n <= 200
Example
Input:
3 4
D _ _ B
_ _ _ _
B _ D _
Output (-1 for non-desk cells):
3 -1 -1 -1
-1 -1 -1 -1
-1 -1 2 -1
Example
Input
3 4
D _ _ B
_ _ _ _
B _ D _
Output
3 -1 -1 -1
-1 -1 -1 -1
-1 -1 2 -1