Skip to the code
cf.
+50 XP

#429 Safest Route Past Hazards

hard

A robot moves through a warehouse drawn as a grid of strings, where "H" marks a hazard and "." is open floor. The robot starts in the top-left cell, must end in the bottom-right cell, and moves up, down, left, or right. It may cross any cell, even a hazard.

A cell's safety is its distance to the nearest hazard: |r1 - r2| + |c1 - c2|. A route's safety is the smallest safety of any cell on it, including the start and the end. Write safestRoute(grid) that returns the largest safety any route can have.

The grid has at least one hazard.

Example 1

Input: grid = ["...","...","H.."]
Output: 2

Going along the top row and down the right column keeps the robot at least 2 away from the hazard. The start and end cells are both exactly 2 away, so no route does better.

Example 2

Input: grid = ["H.",".."]
Output: 0

The start cell is a hazard, so every route has safety 0.

Constraints

  • 1 <= rows, cols <= 200
  • At least one cell is "H".
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).