Skip to the code
+25 XP

#412 Shortest Walk Across the Office

medium

An office map app draws the floor as a grid of strings. "S" is where you stand, "E" is the exit, "." is open floor, and "#" is a desk or wall. You can step up, down, left, or right onto any cell that isn't "#".

Write shortestWalk(floor) that returns the fewest steps from "S" to "E", or -1 if the exit can't be reached. There is exactly one "S" and one "E".

Example 1

Input: floor = ["S.#","..#","#.E"]
Output: 4

Go down, right, down, right: (0, 0) → (1, 0) → (1, 1) → (2, 1) → (2, 2).

Example 2

Input: floor = ["S#E"]
Output: -1

The wall between them blocks the only way.

Constraints

  • 1 <= floor.length, floor[i].length <= 100
  • All rows have the same length.
  • Cells are "S", "E", ".", or "#".
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

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