402348: GYM100735 C Power

Memory Limit:64 MB Time Limit:0 S
Judge Style:Text Compare Creator:
Submit:0 Solved:0

Description

C. Powertime limit per test0.25 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard output

Arthur, the superhero of our times, faces a confusing problem.

He almost completed his final mission. Only one step is left - to find the amulet of power. Well, Arthur knows where the amulet is. But it is not so easy to take him. The reason is that the powerful guard kills anybody who tries to steal the amulet. Unfortunately, the guard is much more powerful than Arthur. So if Arthur meets the guard, the end is not too good.

It is known that the amulet of power can not exist for a long time without the owner. So Arthur has to rush.

You are given the matrix which describes the forest. Arthur and the guard can not leave the forest. The forest contains some dangerous animals. For example, snakes or hungry wolfs. No doubt that Arthur and the guard are afraid of these animals.

Assume that Artur's position is (rA;cA) and the guard's position is (rG;cG). r, c describes the row and the column of the matrix. Let's define the guard's moves formally:

if cA < cG, the guard moves cG:  = cG - 1

if cG < cA, the guard moves cG:  = cG + 1 if the guard did not make the previous move (cA = cG or because of dangerous animals) then he moves with the respect to these rules (if it is possible):

if rA < rG, the guard moves rG:  = rG - 1

if rG < rA, the guard moves rG:  = rG + 1

Arthur can move to one of four adjacent cells (row up, row down, column left, column right). Both, Arthur and the guard can't move diagonally. Arthur and the guard move alternatively. The first move is made by Arthur. Arthur and the guard make the same number of moves. That is, if Arthur gets the amulet and he is caught during the next guard's move, then Arthur is killed. Given the description of the forest determine the minimal number of Arthur's steps needed to be made in order to reach the amulet of power.

Input

The first line of each test case contains the number of rows N and the number of columns M in the matrix. (2 ≤ N, M ≤ 25)

The following N lines contains M characters. The j-th character on the i-th line describes the position (i, j) in the matrix.

'A' denotes the Arthur's initial position.

'G' denotes the guard's initial position.

'X' denotes the position occupied by dangerous animals.

'P' denotes the amulet of power.

'.' denotes other cells.

Output

Output single integer R – the minimal numbers of steps needed to be made. If the amulet can not be reached or the Arhur will certainly be caught by the guard, output  - 1.

ExamplesInput
2 2
A.
GP
Output
-1
Input
2 3
A..
GXP
Output
3
Input
2 2
.G
AP
Output
-1

加入题单

算法标签: