본문 바로가기
코딩테스트

[백준] 1913 달팽이 - Python

by CuckooBird 2023. 2. 12.

백준 실버3 1913 달팽이 - Python

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

 

1913번: 달팽이

N개의 줄에 걸쳐 표를 출력한다. 각 줄에 N개의 자연수를 한 칸씩 띄어서 출력하면 되며, 자릿수를 맞출 필요가 없다. N+1번째 줄에는 입력받은 자연수의 좌표를 나타내는 두 정수를 한 칸 띄어서

www.acmicpc.net


문제


코드

맞았습니다가 뜬 코드입니다. - 메모리 70180KB | 시간 1040ms | 코드 길이 1198B

import sys
input = sys.stdin.readline

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

# 가운데 1 채우기
x = (n - 1) // 2
y = (n - 1) // 2
snail[x][y] = 1

# 방향벡터 (상, 하, 좌, 우)
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]

i = 2
start = 3

while x != 0 or y != 0:
    while i <= start * start:
        if x == y == (n - 1) // 2: # 시작점이면 cnt 세팅, 한 칸 위로
            cnt_up, cnt_down, cnt_left, cnt_right = start, start - 1, start - 1, start - 2
            x += dx[0]
            y += dy[0]
            cnt_up -= 1

        elif cnt_right > 0: # 우
            x += dx[3]
            y += dy[3]
            cnt_right -= 1

        elif cnt_down > 0: # 하
            x += dx[1]
            y += dy[1]
            cnt_down -= 1

        elif cnt_left > 0: # 좌
            x += dx[2]
            y += dy[2]
            cnt_left -= 1

        elif cnt_up > 0: # 상
            x += dx[0]
            y += dy[0]
            cnt_up -= 1

        snail[x][y] = i
        i += 1

    n -= 2
    start += 2

for j in range(len(snail)):
    print(*snail[j])
    if m in snail[j]:
        mx = j + 1
        my = snail[j].index(m) + 1
print(mx, my)

Search 🔍

후기

방향백터를 만든 점이 인상깊네요 저번에 풀었던 거북이 문제도 생각나고..

요놈을 이제야 풀었다.. 다음 문제를 내러가야겠군요..