[알고리즘/백준] 3190번 : 뱀(python)

유현민·2022년 5월 27일
0

알고리즘

목록 보기
189/253

  1. 1초씩

  2. 사과가 없으면 몸 전체 이동
    2-1. 몸은 deque를 써서 넣어주고 사과 없으면 맨 앞에 빼준다.
    2-2. 만약 현재 좌표가 deque안에 없으면 넣어주고 있으면 종료
    2-3. dx, dy를 만들어 0~3으로 처리

  3. 사과가 있으면 deque안에 넣어준다.

  4. 사과 위치는 2차원 리스트를 만들어 1로 표시해준다.(시작 좌표가 1,1이기 때문에 -1해서 넣어야함.)

  5. 회전은 +1, -1로 처리

  6. 탈출 조건은 exit()로 처리
    6-1. 몸에 닿거나 벽이거나
    6-2. 몸은 in deque로 처리
    6-2. 벽은 0 <= nx, ny < N 으로 처리

from collections import deque


def loc(x, y):
    if 0 <= x < N and 0 <= y < N:  # 범위 안에 있으면
        if (x, y) in body:  # 몸이랑 닿으면
            print(time)
            exit()
        elif apple[x][y]:  # 사과 만남
            body.append((x, y))
            b_visited[x][y] = 1
            apple[x][y] = 0
        else:  # 사과 없음
            body.append((x, y))
            body.popleft()
    else:  # 벽 밖으로 나감
        print(time)
        exit()


N = int(input())
apple = [[0] * N for _ in range(N)]  # 사과 위치

for _ in range(int(input())):
    x, y = map(int, input().split())
    apple[x - 1][y - 1] = 1

rot = {}  # 돌아야할 방향이랑 초
for _ in range(int(input())):
    a, b = input().split()
    rot[int(a)] = b

b_visited = [[0] * N for _ in range(N)]  # 몸 위치
time = 1  # 초
body = deque()  # 몸 위치 queue
body.append((0, 0))
b_visited[0][0] = 1  # 몸 위치 체크
x, y = 0, 0
locate = 0  # 바라보는 방향
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]

while True:
    x += dx[locate]
    y += dy[locate]
    # 한칸 움직이기(바라보고 있는 방향에 따라서)
    loc(x, y)

    if time in rot: # 회전
        if rot[time] == 'D':
            locate = (locate + 1) % 4
        else:
            locate = (locate - 1) % 4

    time += 1
profile
smilegate megaport infra

0개의 댓글