Skip to the code
cf.
+50 XP

#433 Collect Keys to Reach the Exit

hard

A browser escape-room game draws its level as a grid of strings. "S" is the start, "E" is the exit, "." is floor, and "#" is a wall. The lowercase letters "a", "b", and "c" are keys, and the uppercase letters "A", "B", and "C" are doors. You pick up a key by stepping onto it, and you may step onto a door only if you already hold its matching key. Keys are never used up.

You move up, down, left, or right, one cell per step. Write stepsToExit(level) that returns the fewest steps from "S" to "E", or -1 if the exit can't be reached.

Example 1

Input: level = ["S#E",".#A","a.."]
Output: 6

Walk down to key a (2 steps), then right along the bottom (2 more), then up through door A to the exit (2 more).

Example 2

Input: level = ["SA.E","....","...."]
Output: 5

Without key a, door A blocks the top row, so walk around below it: down, right 3 times, up.

Constraints

  • 1 <= level.length, level[i].length <= 30
  • Exactly one "S" and one "E".
  • Keys and doors only use the letters a, b, c and A, B, C.
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).