Problem

Closest Bathroom / Desk on a Grid

SnowflakePHONE SCREEN
See Snowflake hiring insights

You are given a two-dimensional office grid. Each cell contains one of three characters:

  • 'B': a bathroom
  • 'D': a desk
  • '_': an empty cell

Movement is allowed in the four cardinal directions, and the base version has no obstacles. For every desk cell, compute the shortest step distance to any bathroom.

Return an integer matrix with the same dimensions as grid. For cells containing desks, store the nearest-bathroom distance. For non-desk cells, store -1. If the grid has no bathrooms, every desk distance should be -1.

Examples
01 · Example 1
grid = [["B", "_", "D"], ["_", "D", "_"], ["D", "_", "B"]]
return = [[-1, -1, 2], [-1, 2, -1], [2, -1, -1]]

Each desk is two steps away from the nearest bathroom using 4-directional movement.

02 · Example 2
grid = [["D", "_"], ["_", "D"]]
return = [[-1, -1], [-1, -1]]

There are no bathrooms in the grid, so no desk has a reachable bathroom.

Constraints
  • grid is a rectangular matrix.
  • Each cell is one of "B", "D", or "_".
  • Movement uses four directions: up, down, left, and right.
More Snowflake problems
drafts saved locally
public int[][] closestBathroomDistances(String[][] grid) {
  // write your code here
}
grid[["B", "_", "D"], ["_", "D", "_"], ["D", "_", "B"]]
expected[[-1, -1, 2], [-1, 2, -1], [2, -1, -1]]
sign in to submit