All problems

Teleporter Maze

Medium · graph traversal

You are given a maze as a rectangular grid of characters:

One step moves you to a neighbouring cell above, below, left or right, as long as it is inside the grid and not a wall. Letter cells and the "E" cell can be walked on like floor. Stepping onto a teleporter does not move you anywhere by itself. But when you are standing on a teleporter, you can also spend one step to jump to the other cell with the same letter.

Return the smallest number of steps needed to get from "S" to "E", or -1 if the exit cannot be reached.

Examples

Example 1

Input: grid = [["S", ".", "E"]]

Output: 2

Walk right twice.

Example 2

Input: grid = [["S", ".", ".", ".", "a", "#", "E"], ["#", "#", "#", "#", "#", "#", "a"]]

Output: 6

Walk four steps right to the first a, spend one step to jump to the other a in the second row, then take one step up to E. Without the teleporter there is no way to the exit.

Example 3

Input: grid = [["S", "#", "E"]]

Output: -1

The wall blocks the only way to the exit.

Constraints