A building's evacuation map marks every room with the number of steps to the closest exit gate. The floor plan is a grid; from a cell you can step up, down, left or right, never diagonally and never through a wall.
The plan floor is an array of strings of equal length, one string per row. Each character is:
"#": a wall
"G": an exit gate
".": an open room
Write two functions that take floor:
gateDistances(floor) returns a grid of numbers with the same shape: 0 for a gate, -1 for a wall, and for each room the fewest steps to any gate. A room that no gate can reach gets Infinity.
nearestGates(floor) returns a grid where each gate and each room holds the number of its nearest gate. Gates are numbered 0, 1, 2, … in reading order (row by row, left to right). A gate's own number is itself. Walls and rooms no gate can reach get -1.
Rules:
Steps go through open rooms only. Gates are where paths start, so a path never passes through another gate (it would have been closer to that gate anyway).
If several gates are equally close to a room, nearestGates picks the one with the smallest number.
An empty plan [] returns []. A plan without gates is valid: every room is unreachable.
If floor is not an array of equal-length strings made only of #, G and ., throw a TypeError.
Plans can be 800 × 800 with more than a thousand gates. Searching from each gate (or each room) separately is far too slow; aim for O(rows × columns).