1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| import sys import heapq as h input = sys.stdin.readline
if __name__ == '__main__': N, M = list(map(lambda x: int(x), input().split(' '))) board = '' for i in range(N): board += input()[:-1]
def move_marble(board_temp): moved_list = [] dxdy = (-1, 1, -M, M) for d in range(len(dxdy)): board_ = board_temp[::] RB = [board_.index('R'), board_.index('B')]
def get_idx(A): return A % M if d < 2 else A // M
move_i = ((0 if get_idx(RB[0]) < get_idx(RB[1]) else 1) + d) % 2
for k in range(2): move_i = (move_i + k) % 2
while 0 <= get_idx(RB[move_i] + dxdy[d]) < M and board_[RB[move_i] + dxdy[d]] == '.': board_[RB[move_i]], board_[RB[move_i] + dxdy[d]] = '.', board_[RB[move_i]] RB[move_i] += dxdy[d]
if 0 <= get_idx(RB[move_i] + dxdy[d]) < M and board_[RB[move_i] + dxdy[d]] == 'O': board_[RB[move_i]] = '.' RB[move_i] = -1
if RB[0] == -1 and RB[1] != -1: return None elif RB[0] != -1 and RB[1] != -1 and ''.join(board_temp) != ''.join(board_): moved_list.append(board_)
return moved_list
bfs = [(1, list(board))] answer = -1 while bfs: count, next_board = h.heappop(bfs) if count > 10: break
moved = move_marble(next_board) if moved is None: answer = count break else: for new_board in moved: h.heappush(bfs, (count + 1, new_board))
print(answer)
|