백준 구현 대비 뱀

yjkim·2023년 7월 2일
0

알고리즘

목록 보기
21/59

접근

deque 자료구조를 활용하여 구현 다음 향할 좌표를 큐의 맨 앞에 넣어주고 꼬리를 큐의 맨 뒤에서 빼는 연산을 통해 문제 해결
초기 time 값을0으로 해주어서 몇번 에러가 났었던 문제, 구현과 시뮬레이션 문제를 풀때 초기 데이터를 정확하게 설정할 수 있도록 신경써야함.

from collections import deque
direction=[[0,1],[1,0],[0,-1],[-1,0]]
curdir=0
time=1
N=int(input())
K=int(input())
dirchange=[]
graph=[[0 for i in range(N)] for j in range(N)]

for i in range(K):
  a,b=map(int, input().split())
  graph[a-1][b-1]='a'

L=int(input())

for i in range(L):
  a,b=input().split()
  a=int(a)
  dirchange.append([a,b])
graph[0][0]='S'

queue=deque()
queue.append([0,0])


while True:
  ni,nj=queue[0][0]+direction[curdir][0],queue[0][1]+direction[curdir][1]
  queue.appendleft([ni,nj])
  if 0<=ni<N and 0<=nj<N and graph[ni][nj]!='S':
    if graph[ni][nj]=='a':
      graph[ni][nj]='S'
    else:
      m=queue.pop()
      graph[m[0]][m[1]]=0
      graph[ni][nj]='S'
  else:
    break

  if len(dirchange)>0 and time==dirchange[0][0]:
    if dirchange[0][1]=='D':
      curdir=(curdir+1)%4
    else:
      curdir=(curdir+3)%4
    dirchange.pop(0)
  time+=1

print(time)
profile
컴퓨터 공부 / 백엔드 개발

0개의 댓글