https://www.acmicpc.net/problem/1726
1726번: 로봇
많은 공장에서 로봇이 이용되고 있다. 우리 월드 공장의 로봇은 바라보는 방향으로 궤도를 따라 움직이며, 움직이는 방향은 동, 서, 남, 북 가운데 하나이다. 로봇의 이동을 제어하는 명령어는
www.acmicpc.net
<문제>
<풀이>
로봇이 바라보는 방향에 따라서 갈 수 있는 노드가 달라진다 -> 3차원 그래프다 (세로 m, 가로 n, 높이가 4인)
이 발상만 빠르게 해낸다면 평범한 BFS 문제가 된다.
하나의 노드에서 최대 5개의 노드와 연결이 가능하다(회전 2방향, 전진 3방향) 하지만 2칸 이상 전진했을때, 앞선 칸이 1이면 넘어가지 못한다. (점프를 할 수 없다)
이것만 주의하고 BFS 탐색을 하면 쉽게 결과를 낼 수 있다.
<코드>
# east 0 west 1 south 2 north 3
from collections import deque
def bfs(start):
bfsQ = deque()
bfsQ.append(start)
isVisited[start[0]][start[1]][start[2]] = True
count[start[0]][start[1]][start[2]] = 0
while(bfsQ):
node = bfsQ.popleft()
currentDir = node[2]
currentCount = count[node[0]][node[1]][node[2]]
if node == end:
return currentCount
for dir in rotate[currentDir]:
if end == [node[0], node[1], dir]:
return currentCount + 1
if isVisited[node[0]][node[1]][dir]:
continue
isVisited[node[0]][node[1]][dir] = True
count[node[0]][node[1]][dir] = currentCount + 1
bfsQ.append((node[0], node[1], dir))
if currentDir == 0:
moves = [(0, 1), (0, 2), (0, 3)]
elif currentDir == 1:
moves = [(0, -1), (0, -2), (0, -3)]
elif currentDir == 2:
moves = [(1, 0), (2, 0), (3, 0)]
else:
moves = [(-1, 0), (-2, 0), (-3, 0)]
for move in moves:
row = node[0] + move[0]
column = node[1] + move[1]
if end == [row, column, currentDir]:
return currentCount + 1
if row < 0 or row >= m or column < 0 or column >= n:
continue
if isVisited[row][column][currentDir]:
continue
if graph[row][column] == 1:
break
isVisited[row][column][currentDir] = True
count[row][column][currentDir] = currentCount + 1
bfsQ.append((row, column, currentDir))
graph = []
rotate = {0: [2, 3],
1: [2, 3],
2: [0, 1],
3: [0, 1]}
m, n = map(int, input().split())
for _ in range(m):
graph.append(list(map(int, input().split())))
start = list(map(int, input().split()))
end = list(map(int, input().split()))
for i in range(3):
start[i] -= 1
end[i] -= 1
isVisited = [[[False] * 4 for i in range(n)] for j in range(m)]
count = [[[0] * 4 for i in range(n)] for j in range(m)]
print(bfs(start))
'Problem Solving > Python' 카테고리의 다른 글
[백준]BOJ 14658: 하늘에서 별똥별이 빗발친다 - Python, Brute force (0) | 2024.04.07 |
---|---|
[백준]BOJ 10159: 저울 - Python, Floyd-Warshall (0) | 2024.04.07 |
[백준]BOJ 3055 - 탈출 - Python/BFS (0) | 2022.11.17 |
[백준]BOJ 7576 - 토마토 - Python/BFS (0) | 2022.11.10 |
[백준]BOJ 1697 - 숨바꼭질 - Python/BFS (0) | 2022.11.07 |
댓글