Baek_3190

원성혁·2022년 10월 7일
0

algorithm

목록 보기
6/21
post-thumbnail

요즘 삼성맨을 꿈꾸며 시뮬레이션 연습중이다.
어제 시도했던 문제인데 일단 실패다......
나는 2차원 배열에 뱀의 위치를 1로 찍었는데 이유는 모르겠지만 실패더라?
물론 기리 증강이나 꼬리제거 그 둘의 순서를 잘 모르겠기는 한데....
이게 동시에 이루어질려면 큐를 써야하나?
찾아보니 다들큐를 썼더라.

import sys
input = sys.stdin.readline
from collections import deque

n = int(input())
cnt = int(input())
matrix = [[0 for i in range(n)]for j in range(n)]
for i in range(cnt):
    a,b = map(int,input().split())
    matrix[a-1][b-1] = 2
cnt2 = int(input())
dq = deque()
for i in range(cnt2):
    num,d = map(str,input().split())
    dq.append((int(num),d))
dir,num = 0,0
head = [0,0]
tail = [0,0]
matrix[0][0] = 1
while True:
    if dq and dq[0][0] ==num:
        a,b = dq.popleft()
        if b == 'D':
            dir+=1
            if dir == 4:
                dir = 0
        else:
            dir -=1
            if dir == -1:
                dir = 3
    if dir == 0:
        head[1]+=1
    elif dir == 1:
        head[0]+=1
    elif dir == 2:
        head[1] -= 1
    else:
        head[0] -= 1
    x,y = head[0],head[1]
    if x<0 or y < 0 or x>=n or y >=n or matrix[x][y] == 1:
        break
    else:
        if matrix[x][y] == 0:
            matrix[x][y] = 1

            xt,yt = tail[0],tail[1]
            matrix[xt][yt] = 0
            for p,q in [[0,1],[1,0],[-1,0],[0,-1]]:
                xtp,ytq = xt+p,yt+q
                if 0<=xtp<n and 0<=ytq<n and matrix[xtp][ytq] == 1:
                    tail[0],tail[1] = xtp,ytq
                    break
        else:
            matrix[x][y] = 1
    num+=1
print(num+1)

이건 내 코드인데. 일단 틀렸다ㅠ 솔직히 왜인지는 잘 모르겠다...
예제는 다 맞췄는데... 나는 글대로 머리를 먼저 움직이고 꼬리를 짜를지 말지 결정인데
꼬리를 짜를껀데 머리랑 닿았을때 오류를 뱉어서 터지나????
근데 찾아보니 다들 뱀을 큐로 구현했더라...
근데 생각해보면 큐가 좋다...
머리의 위치는 새롭게 바뀌니 append해주고 꼬리의 위치는 매번 빼거나 두거나 둘중 하나니
popleft해주는거 같더라...
가장 깔끔하게 짜신 분꺼를 거의 그대로 구현하면서 공부했다.

import sys
input = sys.stdin.readline
from collections import deque

dy = [-1,0,1,0]
dx = [0,1,0,-1]

def change(d,c):
    if c == 'L':
        d = (d-1) % 4
    else:
        d = (d+1) % 4
    return d

def start():
    dir = 1
    time = 1
    y , x = 0,0
    snake = deque([[y,x]])
    matrix [y][x] = 2
    while True:
        y,x = y+dy[dir],x+dx[dir]
        if 0<=y<n and 0<=x<n and matrix[y][x] != 2:
            if not matrix[y][x] == 1:
                temp_y,temp_x = snake.popleft()
                matrix[temp_y][temp_x] = 0
            matrix[y][x] = 2
            snake.append([y,x])
            if time in times.keys():
                dir = change(dir,times[time])
            time+=1
        else:
            return time

if __name__ == '__main__':
    n = int(input())
    k = int(input())
    matrix = [[0]*n for _ in range(n)]
    for _ in range(k):
        a,b = map(int,input().split())
        matrix[a-1][b-1] = 1
    l = int(input())
    times = {}
    for i in range(l):
        x,c = input().split()
        times[int(x)] = c
    print(start())

일단 함수화 하니까 보기 좋더라...
나는 -1%4 = 3 인거 오늘 알았다... 진짜 신기하넴
이건 솔직히 어려울거는 없는데
제한시간안에 이렇게 깔끔하게 짜는건 어렵다ㅠ

일단 이 코드는 재밌던건 time을 dictionary화 해서 dictionary의 key.items()리스트에 지금 현재 시간이 되면 실행하도록 했다.. 참신하다
나였으면 그 리스트 좋자 set으로 바꾸고 찾아봤으려나
시간이 오래걸리지는 않나보다.
암튼 핵심은 큐구조를 사용해 뱀을 만들었고 이동위치 먼저 범위안에 들고 뱀의 몸통이랑 안닿는지 확인하고 그 다음 사과가 있냐 없냐에 따라 popleft할지 말지 결정한다.

시뮬레이션 또 도전할 계획인데 잘하고싶다.

profile
AI개발자를 향해 전진중

0개의 댓글