문제풀이/SW Expert Academy

[SWEA][D2] 1954. 달팽이 숫자 (파이썬/Python)

얄루몬 2021. 9. 24. 21:55

t = int(input())
for tc in range(1, t+1):
    n = int(input())

    space = [[0]*n for _ in range(n)]

    #위, 오른쪽, 아래, 왼쪽으로 움직이는 방향전환
    dx = [0,1,0,-1]
    dy = [1,0,-1,0]
    
    direction = 0
    
    #초기 좌표
    x = y = 0 
    #space[0][0] = 1 부터 돌면서 진행하기 위함
    space[x][y] = 1

    for num in range(2, n*n+1):
        x += dx[direction]
        y += dy[direction]

        #2부터 숫자 넣기.
        space[x][y] = num

        #범위를 확인해주는 작업 범위를 넘어가지 않으면 계속해서 같은 방향성을 가지고 달팽이가 움직인다.
        if 0 <= x + dx[direction] < n and 0 <= y + dy[direction] < n and not space[x+dx[direction]][y+dy[direction]]:
            continue

        #설정 범위를 벗어난다면 dx dy의 방향을 다음으로 바꿔줌 
        if direction != 3:
            direction += 1
        else:
            direction = 0
    print(f'#{tc}')  
    for i in space:
        print(*i)