```
N,M = map(int,input().split())
board = []
balls = {}
for i in range(N):
line = [c for c in input().strip()]
board.append(line)
for j in range(len(line)):
if line[j] in ['R','B']:
balls[line[j]] = [i,j]
board[i][j] = '.'
# Backtracking
def tilt(dirs, balls):
# dirs 0-right 1-up 2-left 3-down
dx, dy = [[1,0],[0,1],[-1,0],[0,-1]][dirs]
rx,ry = balls['R']
bx,by = balls['B']
reached = []
new_balls = {}
for color, [x,y] in balls.items():
while 0<=x+dx<N and 0<=y+dy<M:
if board[x+dx][y+dy] == '#':
break
elif board[x+dx][y+dy] == 'O':
x += dx
y += dy
reached.append(color)
break
x += dx
y += dy
new_balls[color] = [x,y]
if new_balls['R'] == new_balls['B']:
if (rx-bx)*dx < 0:
new_balls['R'][0] -= dx
elif (rx-bx)*dx > 0:
new_balls['B'][0] -= dx
if (ry-by)*dy < 0:
new_balls['R'][1] -= dy
elif (ry-by)*dy > 0:
new_balls['B'][1] -= dy
if new_balls['R']==[rx,ry] and new_balls['B']==[bx,by]:
return -1,{}
if 'B' in reached:
return -1, {}
elif 'R' in reached:
return 1, {}
else:
return 0, new_balls
def solve(tries, balls):
if tries == 11:
return 11
else:
new_tries = []
for i in range(4):
res, new_balls = tilt(i, balls)
if res == 1:
return tries
if res == 0:
new_tries.append(new_balls)
if len(new_tries) == 0:
return 11
else:
return min([solve(tries+1,bs) for bs in new_tries])
result = solve(1,balls)
if result == 11:
print(-1)
else:
print(result)
```