Skip to the code
cf.
+10 XP

#426 Distance to the Nearest Charger

easy

An office app shows, for every desk, how many steps it is to the nearest charging station. The floor is a grid of strings: "C" is a charger, "." is open floor, and "#" is a wall. You can step up, down, left, or right, but not through walls.

Write chargerDistances(floor) that returns a grid of numbers with the same shape: each open cell or charger gets the fewest steps to the nearest charger (chargers get 0). Walls, and cells that can't reach any charger, get -1.

Example 1

Input: floor = ["C..",".#.","..C"]
Output: [[0,1,2],[1,-1,1],[2,1,0]]

Each cell takes the closer of the two chargers. The wall stays -1.

Example 2

Input: floor = ["C#."]
Output: [[0,-1,-1]]

The wall cuts off the last cell, so it can't reach a charger.

Constraints

  • 1 <= floor.length, floor[i].length <= 200
  • Each cell is "C", ".", or "#".
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).