백준 3190번 뱀

JooYong Lee·2022년 1월 27일
0

문제풀이

목록 보기
15/25

2021년 05월 23일


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

3190번 뱀

요약

n*n 맵에서 직진을 하는 길이 1짜리 뱀이 있다

명령이 들어오면 방향을 바꾼다

사과를 먹으면 몸이 길어진다

뱀은 몇초나 살아있는지 구하면 된다

가장 왼쪽 위에서 시작해서 오른쪽 방향으로 1초에 1칸씩 전진
벽이나 자기 자신에 닿으면 끝
사과 먹으면 길이 + 1
전진했을 때 사과를 먹었으면 앞에 추가, 안먹었으면 앞에 추가, 뒤 제거
그러다가 x초 뒤에 좌, 우 회전 명령이 들어오면 방향 전환

from sys import stdin
from collections import deque

n = int(stdin.readline())
k = int(stdin.readline())
g = [[0 for i in range(n)] for j in range(n)]
for i in range(k):
  x,y = map(int, stdin.readline().split())
  g[x-1][y-1] = 'a'
  
L = int(stdin.readline())
com = deque()
for i in range(L):
  com.append(stdin.readline().split())
  
timer = 0

d = {0:(0,1), 1:(1,0), 2:(0,-1), 3:(-1,0)} #0:오른 1:아래 2:왼 3:위
snake = deque()
snake.append((0,0)) #시작 위치
g[0][0] = 1
now_d = 0 #현 방향
while True:
  timer+=1
  next_pos = (snake[0][0]+d[now_d][0], snake[0][1]+d[now_d][1]) #다음 위치
  if (next_pos[0]>=n or next_pos[0]<0) or (next_pos[1]>=n or next_pos[1]<0) or (g[next_pos[0]][next_pos[1]]==1): #범위 안에 없거나 자기 몸에 닿았을 때
    break
  else:
    if g[next_pos[0]][next_pos[1]] == 'a': #사과가 있으면
      g[next_pos[0]][next_pos[1]] = 1
      snake.appendleft(next_pos)
    else:  #사과가 없으면

      g[next_pos[0]][next_pos[1]] = 1
      snake.appendleft(next_pos)
      
      tail = snake.pop()
      g[tail[0]][tail[1]] = 0
    
    if com and timer == int(com[0][0]):
      turn = com.popleft()
      if turn[1] == 'L': #좌회전
        now_d = (now_d + 3) % 4
      else:  #우회전
        now_d = (now_d + 1) % 4

print(timer)
profile
21.11.01~ 기록

0개의 댓글