Problem 579080 · medium · Level 05 Advanced Algorithms & Graphs

Distance to the Nearest Charging Station

grids · BFS · multi-source

A robot vacuum's floor plan is a grid plan of single-character strings: "#" is a wall, "S" is a charging station and "." is open floor. From an open cell the robot moves to side-adjacent non-wall cells. Return a grid of integers of the same shape in which every open cell holds the smallest number of moves to any station, every station holds 0, and walls and open cells that cannot reach a station hold -1.

Examples

Input:  plan = [[".", "#", "S", "."],
                [".", ".", ".", "#"],
                [".", "#", ".", "."],
                ["S", ".", "#", "."]]
Output: [[3, -1, 0,  1],
         [2,  2, 1, -1],
         [1, -1, 2,  3],
         [0,  1, -1, 4]]

Input:  plan = [[".", "."]]
Output: [[-1, -1]]
Explanation: there is no station, so nothing can be reached.

Constraints

  • 1 <= rows, cols <= 60
  • Target O(rows * cols) time.

Goals

  • Seed a BFS with several sources at distance 0
  • Produce a full distance grid while respecting walls
Starting Python…