Algorithm/python 백준

파이썬 백준 3190번 : 뱀

✿(๑❛ڡ❛๑)✿ 2024. 5. 29. 14:39
728x90
SMALL

문제

https://www.acmicpc.net/problem/3190

 

 

풀이

뱀의 좌표를 deque에 넣어서 관리한다. 이후는 문제의 조건대로 구현하면 되는 문제였다. 

import sys
from collections import deque

N=int(sys.stdin.readline())
K=int(sys.stdin.readline())
apple=[]
turn=deque()
snake=deque()
go=[(0,1),(1,0),(0,-1),(-1,0)] # 이동 방향 오른쪽, 아래, 왼쪽, 위
snake.append((1,1))
for _ in range(K): #사과 좌표 저장
    x,y=map(int,sys.stdin.readline().split())
    apple.append((x,y))

L= int(sys.stdin.readline())
i=0
for _ in range(L): #사과 좌표 저장
    x,y=map(str,sys.stdin.readline().split())
    turn.append((int(x),y))

#print(apple, turn)
time=0
next_turn=turn.popleft()
while True:
    time+=1
    x, y = snake[-1]  # snake의 머리 좌표
    x += go[i][0]
    y += go[i][1]

    # 종료 조건
    if (x, y) in snake:  # 머리가 뱀에 닿는 경우
        print(time)
        break
    if x>N or x<=0 or y>N or y<=0 : #맵밖으로 나가는 경우
        print(time)
        break

    if (x,y) not in apple: # 사과가 아니라면 꼬리 이동
        snake.popleft()
    else :
        for a in range(len(apple)):
            if (x,y)==apple[a]:
                apple.pop(a)
                break

    snake.append((x, y))

    if next_turn!=0 and time ==next_turn[0]:
        if next_turn[1]=='D':
            i=(i+1)%4
        else:
            i=(i-1)%4

        if len(turn)!=0:
            next_turn=turn.popleft()
        else:
            next_turn=0

 

 

 

 

덧) 예제 3이 잘 이해되지 않았는데.. 꼬리이동보다 머리 이동이 더 빠른것 같다.. @-@

728x90
LIST