Marble Escape 4

On a small board with one red marble, one blue marble, and a single hole, tilt until the red marble falls through the hole while the blue never does; report the fewest tilts or -1.

Medium7BFSSimulationGraphImplementationInterviewNo attempts yetTime limit2sMemory limit512 MB

Problem

A rectangular board holds one red marble and one blue marble. You tilt the board to roll the red marble out through the hole.

The board is NN rows tall and MM columns wide, divided into cells of size 1×11 \times 1. The outermost rows and columns are blocked, and the board has one hole. The red marble and the blue marble each fill one 1×11 \times 1 cell completely, and there is one of each on the board. The goal is to drop the red marble through the hole. The blue marble must not fall into the hole.

You cannot touch the marbles with your hands, so you roll them with gravity. Four moves are available: tilt left, tilt right, tilt up, tilt down.

Both marbles move at the same time during a move. Dropping the red marble into the hole is a success, and dropping the blue marble into the hole is a failure. Dropping both marbles into the hole at once is also a failure. The red marble and the blue marble cannot share a cell, and each one takes up a whole cell. A tilt lasts until the marbles stop moving.

Given the state of the board, write a program that finds the smallest number of tilts needed to drop the red marble through the hole.

Input

The first line contains two integers NN and MM, the height and the width of the board. (3N,M103 \le N, M \le 10)

Each of the next NN lines contains a string of length MM describing one row of the board. The string consists of '.', '#', 'O', 'R', and 'B'. '.' is an empty cell, '#' is an obstacle or a wall that a marble cannot pass, and 'O' is the position of the hole. 'R' is the position of the red marble and 'B' is the position of the blue marble.

Every board in the input has '#' along its whole border. There is one hole, and there is always one red marble and one blue marble.

Output

Print the smallest number of tilts needed to drop the red marble through the hole. If no sequence of moves drops the red marble through the hole, print -1.