SW Expert

[SWEA] 1954 달팽이 숫자 Python

꿀떡최고 2021. 5. 19. 10:24
반응형

[ 문제 ]

 

난이도:  D2

문제 번호:  1954

 

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5PobmqAPoDFAUq&categoryId=AV5PobmqAPoDFAUq&categoryType=CODE&problemTitle=1954&orderBy=FIRST_REG_DATETIME&selectCodeLang=ALL&select-1=&pageSize=10&pageIndex=1

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com


 

달팽이는 1부터 N*N까지의 숫자가 시계방향으로 이루어져 있다.

다음과 같이 정수 N을 입력 받아 N크기의 달팽이를 출력하시오.

 

[제약사항]

달팽이의 크기 N은 1 이상 10 이하의 정수이다. (1 ≤ N ≤ 10)

 


 

[ 코드 ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
for tc in range(1int(input())+1):
    N = int(input())
    total = N * N
    arr = [[0* N for _ in range(N)]
    cnt = 1
    # 시작은 좌측 상단
    r = 0
    c = 0
    dr = [01-10]
    dc = [100-1]
    # 오른쪽이 시작이므로 시작점은 0
    now = 0
    while cnt <= total:
        # 범위를 벗어나지 않고 그 안의 숫자가 0일 때
        if 0 <= r < N and 0 <= c < N and not arr[r][c]:
            arr[r][c] = cnt
            cnt += 1
        else:
            # 더해서 초과된 부분을 다시 빼줌
            r -= dr[now]
            c -= dc[now]
            # 인덱스 초과 방지
            now = (now+1) % 4
        r += dr[now]
        c += dc[now]
    print('#{}'.format(tc))
    for i in range(N):
        for j in range(N):
            print(arr[i][j], end=' ')
        print()
cs
반응형