# 3190-뱀

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

1. ( x, y ) 는 현재 머리의 위치입니다.
2. 매초마다 d ( 방향 ) 이 변하는지 검사하고 상황에 맞게 적용해줍니다.
3. ( nx, ny ) 는 다음 머리가 위치할 곳입니다.
4. q 는 현재 뱀의 몸이 존재하는 위치들입니다.
5. 매초마다 ( nx, ny ) 에 자신의 몸이 있거나 벽이라면 시간을 출력하고 마칩니다.
6. ( nx, ny ) 에 아무것도 없다면, q 를 선입선출해줍니다.
7. ( nx, ny ) 에 사과가 있다면, q 를 수정하지 않습니다.

```python
import sys


def solution(n):
    time = 0
    y, x = 0, 0
    q = [(0, 0)]
    dy = [0, 1, 0, -1]
    dx = [1, 0, -1, 0]
    d = 0

    while True:
        # 방향 설정
        for plan in dir_plan:
            if time == plan[0]:
                if plan[1] == 'D':
                    d = (d + 1) % 4
                else:
                    d = (d - 1) % 4

        # 다음 머리 위치 설정
        ny = y + dy[d]
        nx = x + dx[d]

        # 다음 머리가 몸이나 벽이라면 time + 1 출력
        if (ny,nx) in q or ny < 0 or ny >= n or nx < 0 or nx >= n:
            return print(time + 1)

        # 다음 머리가 사과면 자취에 추가만 진행
        elif arr[ny][nx] == 'apple':
            arr[ny][nx] = 0
            q.append((ny,nx))

        # 다음 머리에 아무것도 없으면 자취에 몸 추가 하고 꼬리는 빼자
        else:
            q.append((ny,nx))
            q.pop(0)

        # 시간 위치 업데이트
        time += 1
        y = ny
        x = nx


n = int(input())
arr = [[0] * n for _ in range(n)]

k = int(input())
apples = [list(map(int,sys.stdin.readline().split())) for _ in range(k)]
for apple in apples:
    arr[apple[0] - 1][apple[1] - 1] = 'apple'

l = int(input())
dir_plan = [list(sys.stdin.readline().split()) for _ in range(l)]
for v in dir_plan:
    v[0] = int(v[0])

solution(n)
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://pyohamen.gitbook.io/til/algorithm/boj/3190.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
