728x90
반응형
https://www.acmicpc.net/problem/3190
문제 해결
- board 좌표를 만들어 뱀의 움직임과 사과가 있는 좌표를 구현할 수 있도록 한다.
- 뱀이 있는 곳은 1, 사과가 있는 곳은 2로 값을 놓는다. ( 그 외는 0)
- 방향이 바뀌는 것을 인지해 dictionary를 통해 dict[시간] = '움직이는 방향' 해서 'R'일 경우 'L'일 경우 인덱스 변동으로 방향이 변할 수 있도록 move라는 리스트를 정리한다. ( 동, 남, 서, 북 ) 을 리스트에 놓은다음 R일 경우 +1 L일 경우 인덱스를 -1해서 움직이는 방향을 잡을 수 있도록 한다.
- board에서 벗어나거나 뱀이 자기 자신이 있는 좌표(늘어나서 뱅그르르 돌아 자기가 머리와 꼬리가 맞닿는다거나 하면)와 만나면 break를 통해 끝내도록한다.
CODE
from collections import deque
n = int(input())
k = int(input())
board = [[0 for _ in range(n)] for _ in range(n)] # 지도
for _ in range(k):
a, b = map(int, input().split())
board[a-1][b-1] = 2
l = int(input())
dirDict = dict()
que = deque()
que.append((0,0)) # que에 현재 뱀의 위치를 넣을 것이다.
for i in range(l):
x, c = input().split()
dirDict[int(x)] = c
move = [(0,1),(1,0),(0,-1),(-1,0)]
start_x, start_y = 0,0
board[start_x][start_y] = 1
cnt = 0
direction = 0
def turn(alpha):
global direction
if alpha == 'L':
direction = (direction-1)%4
else:
direction = (direction+1)%4
while True:
cnt += 1
start_x += move[direction][0]
start_y += move[direction][1]
if start_x<0 or start_x >=n or start_y < 0 or start_y >=n:
break
if board[start_x][start_y] == 2:
que.append((start_x,start_y))
board[start_x][start_y] = 1
if cnt in dirDict:
turn(dirDict[cnt])
elif board[start_x][start_y] == 0:
board[start_x][start_y] = 1
que.append((start_x,start_y))
tx,ty = que.popleft()
board[tx][ty] = 0
if cnt in dirDict:
turn(dirDict[cnt])
else:
break
print(cnt)
728x90
반응형
'알고리즘 > [python] 백준 BOJ' 카테고리의 다른 글
[python] 백준 1072 게임 (0) | 2023.03.05 |
---|---|
[python] 백준 5639 이진 검색 트리 (0) | 2023.03.05 |
[python] 백준 2251 물통 (0) | 2023.02.28 |
[python] 백준 1525 퍼즐 (0) | 2023.02.28 |
[python] 백준 18352 특정 거리의 도시 찾기 (0) | 2023.02.26 |
댓글