본문 바로가기
알고리즘/[python] 백준 BOJ

[python] 백준 3190 뱀

by Alan_Kim 2023. 3. 5.
728x90
반응형

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

 

3190번: 뱀

 'Dummy' 라는 도스게임이 있다. 이 게임에는 뱀이 나와서 기어다니는데, 사과를 먹으면 뱀 길이가 늘어난다. 뱀이 이리저리 기어다니다가 벽 또는 자기자신의 몸과 부딪히면 게임이 끝난다. 게임

www.acmicpc.net

 

문제 해결

  • 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
반응형

댓글