|
| 1 | +# 3190 뱀 |
| 2 | +# idea : 1. 자신에 부딪히면 안되므로 뱀을 2로 부여해서 조건을 넣는다. 2. 시간이 되면 방향을 바꿔주어야 하는데 방향벡터로 시계방향 반시계방향을 만들어 놓는다. 3. 덱으로 뱀의 길이조절을 한다. |
| 3 | +import sys |
| 4 | +from collections import deque |
| 5 | + |
| 6 | + |
| 7 | +# index - 0: 북, 1: 동, 2: 남, 3: 서 |
| 8 | +dy = [-1, 0, 1, 0] |
| 9 | +dx = [0, 1, 0, -1] |
| 10 | + |
| 11 | + |
| 12 | +N = int(sys.stdin.readline()) |
| 13 | +K = int(sys.stdin.readline()) |
| 14 | +board = [[0] * N for _ in range(N)] |
| 15 | +for _ in range(K): |
| 16 | + a, b = map(int, sys.stdin.readline().split()) |
| 17 | + board[a-1][b-1] = 1 # 사과 1로 저장 |
| 18 | + |
| 19 | +L = int(sys.stdin.readline()) |
| 20 | + |
| 21 | +times = {} # dictionary |
| 22 | + |
| 23 | +for i in range(L): |
| 24 | + X, C = sys.stdin.readline().split() |
| 25 | + times[int(X)] = C |
| 26 | + |
| 27 | +dir = 1 # 초기의 방향 - default |
| 28 | +time = 1 # 시간 |
| 29 | +y = x = 0 |
| 30 | +snake = deque([[y, x]]) # 방문 위치 |
| 31 | +board[y][x] = 2 # 뱀은 2로 표시 |
| 32 | + |
| 33 | +while True: |
| 34 | + y, x = y + dy[dir], x + dx[dir] |
| 35 | + if 0 <= y < N and 0 <= x < N and board[y][x] != 2: # 보드 안에 있거나, 자신을 만나지 않는 경우 |
| 36 | + if board[y][x] == 0: # 사과가 없는 경우 |
| 37 | + tail_y, tail_x = snake.popleft() # 꼬리를 미리 떼서 뱀 크기 유지 |
| 38 | + board[tail_y][tail_x] = 0 # 꼬리 제거 |
| 39 | + |
| 40 | + board[y][x] = 2 # 진행방향은 뱀으로 바꿈 |
| 41 | + snake.append([y, x]) # 늘려줌. |
| 42 | + if time in times.keys(): # 방향을 바뀔 시간이 되면, |
| 43 | + if times[time] == "D" : # Default일 때 |
| 44 | + dir = (dir+1) % 4 # overflow 방지해서 modulo 사용 |
| 45 | + else: # Left일 때 |
| 46 | + dir = (dir+3) % 4 |
| 47 | + |
| 48 | + time += 1 |
| 49 | + else: # 본인 몸에 부딪히거나, 벽에 부딪힌 경우 종료. |
| 50 | + print(time) |
| 51 | + exit(0) |
| 52 | + |
| 53 | + |
| 54 | + |
| 55 | + |
| 56 | + |
0 commit comments