AtCoder Beginner Contest 184
E
Third Avenue
AtCoder
⌀ 1418
原题
← DF →
翻译中…

Problem Statement

翻译中…

There is a town represented as a two-dimensional grid with $H$ horizontal rows and $W$ vertical columns. A character $a_{i,j}$ describes the square at the $i$-th row from the top and $j$-th column from the left. Here, $a_{i,j}$ is one of the following: S , G , . , # , a, ..., and z. # represents a square that cannot be entered, and a, ..., z represent squares with teleporters.

翻译中…

Takahashi is initially at the square represented as S. In each second, he will make one of the following moves:

翻译中…
  • Go to a non-# square that is horizontally or vertically adjacent to his current position.
  • Choose a square with the same character as that of his current position, and teleport to that square. He can only use this move when he is at a square represented as a, ..., or z.
翻译中…

Find the shortest time Takahashi needs to reach the square represented as G from the one represented as S. If the destination is unreachable, report -1 instead.

翻译中…

Constraints

翻译中…
  • $1 \le H, W \le 2000$
  • $a_{i,j}$ is S, G, ., #, or a lowercase English letter.
  • There is exactly one square represented as S and one square represented as G.
翻译中…

Input

翻译中…

Input is given from Standard Input in the following format:

翻译中…

H W
a_{1,1}\dots a_{1,W}
\vdots
a_{H,1}\dots a_{H,W}

翻译中…

Output

翻译中…

Print the shortest time Takahashi needs to reach the square represented as G from the one represented as S. If the destination is unreachable from the initial position, print -1 instead.

翻译中…

样例

Input #1
2 5
S.b.b
a.a.G
Output #1
4
Let $(i, j)$ denote the square at the $i$-th row from the top and $j$-th column from the left. Initially, Takahashi is at $(1, 1)$. One way to reach $(2, 5)$ in four seconds is: - go from $(1, 1)$ to $(2, 1)$; - teleport from $(2, 1)$ to $(2, 3)$, which is also an `a` square; - go from $(2, 3)$ to $(2, 4)$; - go from $(2, 4)$ to $(2, 5)$.
Input #2
11 11
S##...#c...
...#d.#.#..
..........#
.#....#...#
#.....bc...
#.##......#
.......c..#
..#........
a..........
d..#...a...
.#........G
Output #2
14
Input #3
11 11
.#.#.e#a...
.b..##..#..
#....#.#..#
.#dd..#..#.
....#...#e.
c#.#a....#.
.....#..#.e
.#....#b.#.
.#...#..#..
......#c#G.
#..S...#...
Output #3
-1
题目信息
题号
abc184_e
时间限制
3 s
内存限制
1024 MB

题面与样例版权归 AtCoder 及出题人所有;中文翻译由 AI 生成(CI 管线),如有出入请以原文为准。