메모리: 35472 KB, 시간: 64 ms
구현, 그래프 이론, 그래프 탐색, 시뮬레이션, 너비 우선 탐색, 격자 그래프
스타트링크에서 판매하는 어린이용 장난감 중에서 가장 인기가 많은 제품은 구슬 탈출이다. 구슬 탈출은 직사각형 보드에 빨간 구슬과 파란 구슬을 하나씩 넣은 다음, 빨간 구슬을 구멍을 통해 빼내는 게임이다.
보드의 세로 크기는 N, 가로 크기는 M이고, 편의상 1×1크기의 칸으로 나누어져 있다. 가장 바깥 행과 열은 모두 막혀져 있고, 보드에는 구멍이 하나 있다. 빨간 구슬과 파란 구슬의 크기는 보드에서 1×1크기의 칸을 가득 채우는 사이즈이고, 각각 하나씩 들어가 있다. 게임의 목표는 빨간 구슬을 구멍을 통해서 빼내는 것이다. 이때, 파란 구슬이 구멍에 들어가면 안 된다.
이때, 구슬을 손으로 건드릴 수는 없고, 중력을 이용해서 이리 저리 굴려야 한다. 왼쪽으로 기울이기, 오른쪽으로 기울이기, 위쪽으로 기울이기, 아래쪽으로 기울이기와 같은 네 가지 동작이 가능하다.
각각의 동작에서 공은 동시에 움직인다. 빨간 구슬이 구멍에 빠지면 성공이지만, 파란 구슬이 구멍에 빠지면 실패이다. 빨간 구슬과 파란 구슬이 동시에 구멍에 빠져도 실패이다. 빨간 구슬과 파란 구슬은 동시에 같은 칸에 있을 수 없다. 또, 빨간 구슬과 파란 구슬의 크기는 한 칸을 모두 차지한다. 기울이는 동작을 그만하는 것은 더 이상 구슬이 움직이지 않을 때 까지이다.
보드의 상태가 주어졌을 때, 10번 이하로 빨간 구슬을 구멍을 통해 빼낼 수 있는지 구하는 프로그램을 작성하시오.
첫 번째 줄에는 보드의 세로, 가로 크기를 의미하는 두 정수 N, M (3 ≤ N, M ≤ 10)이 주어진다. 다음 N개의 줄에 보드의 모양을 나타내는 길이 M의 문자열이 주어진다.
입력되는 모든 보드의 가장자리에는 모두 '#'이 있다. 구멍의 개수는 한 개 이며, 빨간 구슬과 파란 구슬은 항상 1개가 주어진다.
파란 구슬을 구멍에 넣지 않으면서 빨간 구슬을 10번 이하로 움직여서 빼낼 수 있으면 1을 없으면 0을 출력한다.
이 문제는 주어진 보드에서 빨간 구슬을 구멍을 통해 빼내는 최소 횟수를 구하는 문제입니다. 단, 파란 구슬이 구멍에 들어가면 안 되며, 최대 10번의 이동 안에 빨간 구슬을 빼내야 합니다. 입력으로는 보드의 크기와 보드 상태가 주어지고, 출력으로는 성공하면 1, 실패하면 0을 출력해야 합니다.
이 문제는 BFS (너비 우선 탐색) 알고리즘을 사용하여 해결할 수 있습니다. BFS는 현재 상태에서 가능한 모든 다음 상태를 탐색하며, 목표 상태에 도달할 때까지 탐색을 반복합니다.
graph 리스트에 저장합니다.R)과 파란 구슬(B)의 초기 위치를 찾고, graph에서 해당 위치를 빈 칸(.)으로 변경합니다.stack)를 초기화하고, 시작 상태 (빨간 구슬 위치, 파란 구슬 위치, 이동 횟수)를 큐에 넣습니다.visited 집합을 초기화하고, 시작 상태를 visited에 추가합니다.#)이나 구멍(O)을 만날 때까지 이동합니다.visited에 없다면, visited에 추가하고 큐에 넣습니다.visited 집합에 저장되는 상태의 수는 최대 O(N*M*N*M)이므로, 공간 복잡도는 O(N^2 * M^2)입니다.visited 집합을 사용하여 이미 방문한 상태는 다시 탐색하지 않도록 하여 시간 효율성을 높입니다.from collections import deque
import sys
n, m = map(int, sys.stdin.readline().split())
graph = [list(sys.stdin.readline().strip()) for _ in range(n)]
for i in range(n):
for j in range(m):
if graph[i][j] == "R":
graph[i][j] = "."
red = (i, j)
if graph[i][j] == "B":
graph[i][j] = "."
blue = (i, j)
redhole = False
bluehole = False
stack = deque([(red, blue, 0)])
visited = set()
visited.add((red[0], red[1], blue[0], blue[1]))
cnt = 0
while stack:
r, b, cnt = stack.popleft()
cnt += 1
if cnt > 10:
break
rx, ry = r[0], r[1]
bx, by = b[0], b[1]
# Left 이동
i = 1
withBlue = False
bluehole = False
redhole = False
while True:
if rx == bx and ry - i == by:
withBlue = True
if graph[rx][ry - i] == ".":
i += 1
elif graph[rx][ry - i] == "O":
redhole = True
left_red = (rx, ry - i)
break
elif graph[rx][ry - i] == "#":
left_red = (rx, ry - i + 1)
break
if withBlue:
bluehole=True
if not redhole:
left_blue = left_red
left_red = (left_red[0], left_red[1] + 1)
if not (left_red[0], left_red[1], left_blue[0], left_blue[1]) in visited:
visited.add((left_red[0], left_red[1], left_blue[0], left_blue[1]))
stack.append((left_red, left_blue, cnt))
else:
i = 1
while True:
if graph[bx][by - i] == ".":
i += 1
elif graph[bx][by - i] == "O":
bluehole = True
break
elif graph[bx][by - i] == "#":
left_blue = (bx, by - i + 1)
break
if redhole and not bluehole:
break
if not bluehole:
if left_red[0] == left_blue[0] and left_red[1] == left_blue[1]:
left_blue = (left_blue[0], left_blue[1] + 1)
if not (left_red[0], left_red[1], left_blue[0], left_blue[1]) in visited:
visited.add((left_red[0], left_red[1], left_blue[0], left_blue[1]))
stack.append((left_red, left_blue, cnt))
# Right 이동
i = 1
bluehole = False
withBlue = False
redhole = False
while True:
if rx == bx and ry + i == by:
withBlue = True
if graph[rx][ry + i] == ".":
i += 1
elif graph[rx][ry + i] == "O":
redhole = True
right_red = (rx, ry + i)
break
elif graph[rx][ry + i] == "#":
right_red = (rx, ry + i - 1)
break
if withBlue:
bluehole=True
if not redhole:
right_blue = right_red
right_red = (right_red[0], right_red[1] - 1)
if not (right_red[0], right_red[1], right_blue[0], right_blue[1]) in visited:
visited.add((right_red[0], right_red[1], right_blue[0], right_blue[1]))
stack.append((right_red, right_blue, cnt))
else:
i = 1
while True:
if graph[bx][by + i] == ".":
i += 1
elif graph[bx][by + i] == "O":
bluehole = True
break
elif graph[bx][by + i] == "#":
right_blue = (bx, by + i - 1)
break
if redhole and not bluehole:
break
if not bluehole:
if right_red[0] == right_blue[0] and right_red[1] == right_blue[1]:
right_blue = (right_blue[0], right_blue[1] - 1)
if not (right_red[0], right_red[1], right_blue[0], right_blue[1]) in visited:
visited.add((right_red[0], right_red[1], right_blue[0], right_blue[1]))
stack.append((right_red, right_blue, cnt))
# Up 이동
i = 1
bluehole = False
withBlue = False
redhole = False
while True:
if rx - i == bx and ry == by:
withBlue = True
if graph[rx - i][ry] == ".":
i += 1
elif graph[rx - i][ry] == "O":
redhole = True
up_red = (rx - i, ry)
break
elif graph[rx - i][ry] == "#":
up_red = (rx - i + 1, ry)
break
if withBlue:
bluehole=True
if not redhole:
up_blue = up_red
up_red = (up_red[0] + 1, up_red[1])
if not (up_red[0], up_red[1], up_blue[0], up_blue[1]) in visited:
visited.add((up_red[0], up_red[1], up_blue[0], up_blue[1]))
stack.append((up_red, up_blue, cnt))
else:
i = 1
while True:
if graph[bx - i][by] == ".":
i += 1
elif graph[bx - i][by] == "O":
bluehole = True
break
elif graph[bx - i][by] == "#":
up_blue = (bx - i + 1, by)
break
if redhole and not bluehole:
break
if not bluehole:
if up_red[0] == up_blue[0] and up_red[1] == up_blue[1]:
up_blue = (up_blue[0] + 1, up_blue[1])
if not (up_red[0], up_red[1], up_blue[0], up_blue[1]) in visited:
visited.add((up_red[0], up_red[1], up_blue[0], up_blue[1]))
stack.append((up_red, up_blue, cnt))
# Down 이동
i = 1
bluehole = False
withBlue = False
redhole = False
while True:
if rx + i == bx and ry == by:
withBlue = True
if graph[rx + i][ry] == ".":
i += 1
elif graph[rx + i][ry] == "O":
redhole = True
down_red = (rx + i, ry)
break
elif graph[rx + i][ry] == "#":
down_red = (rx + i - 1, ry)
break
if withBlue:
bluehole=True
if not redhole:
down_blue = down_red
down_red = (down_red[0] - 1, down_red[1])
if not (down_red[0], down_red[1], down_blue[0], down_blue[1]) in visited:
visited.add((down_red[0], down_red[1], down_blue[0], down_blue[1]))
stack.append((down_red, down_blue, cnt))
else:
i = 1
while True:
if graph[bx + i][by] == ".":
i += 1
elif graph[bx + i][by] == "O":
bluehole = True
break
elif graph[bx + i][by] == "#":
down_blue = (bx + i - 1, by)
break
if redhole and not bluehole:
break
if not bluehole:
if down_red[0] == down_blue[0] and down_red[1] == down_blue[1]:
down_blue = (down_blue[0] - 1, down_blue[1])
if not (down_red[0], down_red[1], down_blue[0], down_blue[1]) in visited:
visited.add((down_red[0], down_red[1], down_blue[0], down_blue[1]))
stack.append((down_red, down_blue, cnt))
if redhole:
if bluehole:
print(0)
else:
print(1)
else:
print(0)