#abc339d. D - Synchronized Players

D - Synchronized Players

Score: 400400 points

问题描述

存在一个 N×NN \times N 的网格,其中每个格子要么为空,要么包含一个障碍物。令 (i,j)(i, j) 表示从上到下的第 ii 行和从左到右的第 jj 列的格子。

网格上还有两个玩家分别位于不同的空格子上。关于每个格子的信息以长度为 NNNN 个字符串 S1,S2,,SNS_1, S_2, \ldots, S_N 的形式给出,格式如下:

  • 如果 SiS_i 的第 jj 个字符是 P,则表示 (i,j)(i, j) 是一个有玩家在上面的空格子。

  • 如果 SiS_i 的第 jj 个字符是 ., 则表示 (i,j)(i, j) 是一个没有玩家的空格子。

  • 如果 SiS_i 的第 jj 个字符是 #,则表示 (i,j)(i, j) 包含一个障碍物。

通过重复以下操作,找出将两名玩家移动到同一格子所需的最小步数。如果无法通过重复该操作将两名玩家移到同一格子,请输出 -1

  • 选择四个方向之一:上、下、左或右。然后,每个玩家尝试向所选方向的相邻格子移动。如果玩家的目的地格子存在且为空,则移动;否则,保持不动。

以上为通义千问 qwen-max 翻译,仅供参考。

Problem Statement

There is an N×NN \times N grid, where each cell is either empty or contains an obstacle. Let (i,j)(i, j) denote the cell at the ii-th row from the top and the jj-th column from the left.

There are also two players on distinct empty cells of the grid. The information about each cell is given as NN strings S1,S2,,SNS_1, S_2, \ldots, S_N of length NN, in the following format:

  • If the jj-th character of SiS_i is P, then (i,j)(i, j) is an empty cell with a player on it.

  • If the jj-th character of SiS_i is ., then (i,j)(i, j) is an empty cell without a player.

  • If the jj-th character of SiS_i is #, then (i,j)(i, j) contains an obstacle.

Find the minimum number of moves required to bring the two players to the same cell by repeating the following operation. If it is impossible to bring the two players to the same cell by repeating the operation, print -1.

  • Choose one of the four directions: up, down, left, or right. Then, each player attempts to move to the adjacent cell in that direction. Each player moves if the destination cell exists and is empty, and does not move otherwise.

Constraints

  • NN is an integer between 22 and 6060, inclusive.
  • SiS_i is a string of length NN consisting of P, ., and #.
  • There are exactly two pairs (i,j)(i, j) where the jj-th character of SiS_i is P.

Input

The input is given from Standard Input in the following format:

NN

S1S_1

S2S_2

\vdots

SNS_N

Output

Print the answer.

Sample Input 1

5
....#
#..#.
.P...
..P..
....#

Sample Output 1

3

Let us call the player starting at (3,2)(3, 2) Player 1 and the player starting at (4,3)(4, 3) Player 2.

For example, doing the following brings the two players to the same cell in three moves:

  • Choose left. Player 1 moves to (3,1)(3, 1), and Player 2 moves to (4,2)(4, 2).

  • Choose up. Player 1 does not move, and Player 2 moves to (3,2)(3, 2).

  • Choose left. Player 1 does not move, and Player 2 moves to (3,1)(3, 1).

Sample Input 2

2
P#
#P

Sample Output 2

-1

Sample Input 3

10
..........
..........
..........
..........
....P.....
.....P....
..........
..........
..........
..........

Sample Output 3

10

update @ 2024/3/10 01:31:32