Fusion
Time limit15sMemory limit512 MB
On a grid with empty cells, blocked cells, and atoms, fuse the two special atoms in the fewest instructions, where each instruction removes two atoms that are adjacent or connected by empty cells.
- Level
Medium7 of 10
- Topics
- Graph, BFS, Shortest path, Implementation
- Solved
- No attempts yet
Problem
The first cold fusion reactor was finished today and cleared for operation. When it was started for the first time, nothing happened.
The physicists checked their calculations over and over, and then three engineers found the cause. Two atoms inside the reactor have become α-stuck.
The reactor can be seen as a grid with rows and columns. Each cell is empty, holds one deuterium atom (two of those atoms are the α-stuck ones), or is blocked off by a control rod that prevents a runaway reaction. Each cell is adjacent to the four cells above it, below it, to its left and to its right, and a cell on the border of the reactor has fewer than four neighbors.
You can give the reactor a fusion instruction by naming two atoms to be fused. The two atoms fuse only if they sit in adjacent cells, or if a path of adjacent empty cells runs from one of them to the other. When two atoms fuse they produce helium that floats away, and both cells they occupied become empty.
To repair the reactor you have to fuse the two α-stuck atoms with each other. What is the fewest number of instructions the reactor needs for that?

Figure 1: the reactor of the first example input. Black cells are blocked off by control rods, blue circles are deuterium atoms, and the yellow circles are the two α-stuck atoms. One optimal sequence of fusions is shown as well.
Will you and your fellow engineers clear the last barrier to cold fusion?
Input
The first line contains two integers and , the number of rows and the number of columns of the reactor (, ).
Each of the next lines describes one row of the reactor and holds exactly characters.
.is an empty cell.#is a cell blocked off by a control rod.Ois a cell holding a deuterium atom.Ais a cell holding an α-stuck atom.
The input holds exactly two A characters.
Output
Print the fewest fusion instructions needed to fuse the two α-stuck atoms with each other. If they cannot be fused, print -1 instead.