Under construction

Still being built. Things may change

Corn Maze

Time limit1sMemory limit128 MB

Summary
Given a grid with walkable cells, zero-cost paired teleporter slides, and one exit, find the minimum time from the start to the exit.
Level

Medium5 of 10

Topics
Graph, BFS, Shortest path, Matrix
Solved
No attempts yet

Problem

Farmer John took his cows to visit a corn maze this past fall. But this was no ordinary corn maze: it contained several gravity-powered teleporter slides that instantly move a cow from one point in the maze to another.

Each slide works in both directions: a cow can slide instantly from a slide's start to its end, or from its end back to its start. If a cow steps onto a cell holding either end of a slide, she must use the slide.

The outside of the maze is entirely corn, except for a single exit.

The maze is an N×MN \times M grid (2≤N≤3002 \le N \le 300, 2≤M≤3002 \le M \le 300). Each cell holds exactly one of the following:

  • Corn — impassable.
  • Grass — easy to walk through.
  • A slide endpoint — teleports a cow to the other endpoint of the same slide.
  • The exit.

A cow can move from one cell to an adjacent cell (up, down, left, or right) only if neither cell is corn. Moving to an adjacent cell takes 11 unit of time; sliding from one endpoint of a slide to its other endpoint takes 00 units of time.

The cells are encoded as follows:

  • Corn: #
  • Grass: .
  • Slide endpoints: a pair of identical uppercase letters (A–Z). Each letter is used by at most one slide, so the two endpoints of a slide share the same letter and no other cell uses that letter.
  • Exit: =
  • Bessie's current cell: @ (this cell is grass).

Bessie is lost. Given her starting cell @, find the minimum time she needs to reach the exit.

Input

  • Line 11: two space-separated integers NN and MM.
  • Lines 2…N+12 \ldots N+1: line i+1i+1 contains MM characters (no spaces) describing row ii of the maze.

Output

  • Line 11: a single integer — the minimum time Bessie needs to reach the exit.

Examples3

  1. Example 1

    Input
    5 6
    ###=##
    #.W.##
    #.####
    #.@W##
    ######
    
    Expected output
    3
    
  2. Example 2

    Input
    4 4
    ####
    #@.#
    #.=#
    ####
    
    Expected output
    2
    
  3. Example 3

    Input
    3 4
    ####
    #@=#
    ####
    
    Expected output
    1