Marble Escape 2

Find the minimum number of tilts that roll the red marble into the hole while the blue marble never falls in.

Medium6BFSSimulationGraphInterviewNo attempts yetTime limit2sMemory limit512 MB

Problem

Marble escape is a game played on a rectangular board that holds one red marble and one blue marble. You win by rolling the red marble out through the hole in the board.

The board is NN cells tall and MM cells wide, divided into cells of size 1×11 \times 1. The outermost rows and columns are blocked, and the board has one hole. Each marble fills a 1×11 \times 1 cell completely, and there is one marble of each color. The goal is to get the red marble out through the hole. The blue marble must not enter the hole.

You cannot touch the marbles with your hands. You tilt the board instead and let gravity roll them. Four moves are available: tilt left, tilt right, tilt up, tilt down.

On a single move both marbles roll at the same time, and they keep rolling until neither can move any further. If the red marble falls into the hole, you succeed. If the blue marble falls into the hole, you fail, and that includes the case where both marbles fall into the hole on the same move. The two marbles never occupy the same cell at the same time.

Given the state of the board, write a program that finds the minimum number of tilts that rolls the red marble out through the hole.

Input

The first line has two integers NN and MM (3N,M103 \le N, M \le 10), the height and the width of the board. Each of the next NN lines has a string of length MM that describes one row of the board. The string consists of ., #, O, R, and B. . is an empty cell, # is a wall or an obstacle 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 cell on the border of the board is #. There is one hole, one red marble, and one blue marble.

Output

Print the minimum number of tilts needed to roll the red marble out through the hole. If ten or fewer tilts cannot do it, print -1.