E. Escaping Cokeman
time limit per test
1 second
memory limit per test
1024 megabytes
input
standard input
output
standard output

Mr. Cokeman is a terrifying figure who roams the halls of the Institute of Mysterious Experiments (IME). It is said that he does unspeakable things to those who stand in his way, but nothing enrages him more than seeing someone in the corridors without their IME badge. If he catches you without it, he'll unleash an ancient forbidden curse known as FATD, and you'll perish instantly.

IME is a rectangular grid of size $$$N \times M$$$ represented by a matrix $$$A$$$. Each element $$$a_{ij}$$$ of the matrix $$$(1 \leq i \leq N, 1 \leq j \leq M)$$$ is an ASCII character and represents the tile $$$(i,j)$$$ of the grid. You start at tile $$$(1, 1)$$$ and must reach the exit at $$$(N, M)$$$. Unfortunately, you left your badge behind at some tile $$$(X, Y)$$$.

Mr. Cokeman walks through IME on a known, fixed route — a connected path of adjacent* tiles, where each tile appears only once in the path. While you don't know where he is at any given moment, stepping on any tile from his route without your badge is certain death. With the badge, you're safe.

You have two options:

  1. Go straight to the exit, avoiding any tile on Cokeman's route.
  2. Retrieve your badge at $$$(X, Y)$$$ first, and then proceed safely to the exit—this allows you to walk through his route.

Considering each move to an adjacent tile takes exactly 1 second, determine the time of the path with minimum time to reach the exit safely. If it's not possible, print -1.

Note that the path of minimum time until the exit must not contain tiles located out of IME's grid.

______________________________

* Two tiles $$$(i_1, j_1)$$$ and $$$(i_2, j_2)$$$ are considered adjacent if and only if $$$|i_1 - i_2| + |j_1 - j_2| = 1$$$.

Input

The first line contains two integers $$$N$$$ and $$$M$$$ ($$$1 \leq N, M \leq 1000$$$) — the number of rows and columns.

The next $$$N$$$ lines each contain a string of length $$$M$$$ representing IME's grid. The $$$j$$$-th character of the $$$i$$$-th string contains the corresponding character of the tile $$$(i,j)$$$.

Each character is either:

  • . — a floor tile you can walk on
  • # — a wall tile you cannot walk through
  • B — the tile where the badge is located (also treated as floor)
  • X — a tile that is part of Mr. Cokeman's route where there is at most one B tile and X tiles form a path of adjacent tiles.
Output

Output a single integer — the minimum time in seconds to safely reach the exit at $$$(N, M)$$$ from $$$(1, 1)$$$, considering the rules. If it is not possible, output -1.

Examples
Input
5 5
...B.
.X...
#X###
.X...
.....
Output
12
Input
5 5
...B.
.X...
.X###
.X...
.....
Output
8
Input
5 5
.X..B
.X...
#X###
.X...
.....
Output
-1