B - Distance Between Tokens Editorial /

Time Limit: 2 sec / Memory Limit: 1024 MB

配点 : 200200

問題文

HHWW 列のマス目があり、そのうち二つの異なるマスに駒が置かれています。

マス目の状態は HH 個の長さ WW の文字列 S1,,SHS_1, \dots, S_H で表されます。Si,j=S_{i, j} = o ならば ii 行目 jj 列目のマスに駒が置かれていることを、Si,j=S_{i, j} = - ならばそのマスには駒が置かれていないことを表します。なお、Si,jS_{i, j} は文字列 SiS_ijj 文字目を指します。

一方の駒をマス目の外側に出ないように上下左右の隣接するマスに動かすことを繰り返すとき、もう一方の駒と同じマスに移動させるためには最小で何回動かす必要がありますか?

制約

  • 2H,W1002 \leq H, W \leq 100
  • H,WH, W は整数
  • Si(1iH)S_i \, (1 \leq i \leq H)o および - のみからなる長さ WW の文字列
  • Si,j=S_{i, j} = o となる整数 1iH,1jW1 \leq i \leq H, 1 \leq j \leq W の組がちょうど二つ存在する

入力

入力は以下の形式で標準入力から与えられる。

HH WW
S1S_1
\vdots
SHS_H

出力

答えを出力せよ。


入力例 1Copy

Copy
2 3
--o
o--

出力例 1Copy

Copy
3

11 行目 33 列目に置かれている駒を 下 \rightarrow\rightarrow 左 と移動すると 33 回でもう一方の駒と同じマスに移動させることができます。22 回以下で移動させることはできないので、33 を出力します。


入力例 2Copy

Copy
5 4
-o--
----
----
----
-o--

出力例 2Copy

Copy
4

Score : 200200 points

Problem Statement

There is a grid with HH horizontal rows and WW vertical columns, in which two distinct squares have a piece.

The state of the squares is represented by HH strings S1,,SHS_1, \dots, S_H of length WW. Si,j=S_{i, j} = o means that there is a piece in the square at the ii-th row from the top and jj-th column from the left; Si,j=S_{i, j} = - means that the square does not have a piece. Here, Si,jS_{i, j} denotes the jj-th character of the string SiS_i.

Consider repeatedly moving one of the pieces to one of the four adjacent squares. It is not allowed to move the piece outside the grid. How many moves are required at minimum for the piece to reach the square with the other piece?

Constraints

  • 2H,W1002 \leq H, W \leq 100
  • HH and WW are integers.
  • Si(1iH)S_i \, (1 \leq i \leq H) is a string of length WW consisting of o and -.
  • There exist exactly two pairs of integers 1iH,1jW1 \leq i \leq H, 1 \leq j \leq W such that Si,j=S_{i, j} = o.

Input

Input is given from Standard Input in the following format:

HH WW
S1S_1
\vdots
SHS_H

Output

Print the answer.


Sample Input 1Copy

Copy
2 3
--o
o--

Sample Output 1Copy

Copy
3

The piece at the 11-st row from the top and 33-rd column from the left can reach the square with the other piece in 33 moves: down, left, left. Since it is impossible to do so in two or less moves, 33 should be printed.


Sample Input 2Copy

Copy
5 4
-o--
----
----
----
-o--

Sample Output 2Copy

Copy
4


2025-04-17 (Thu)
02:42:33 +00:00