본문으로 바로가기


SW Expert Academy 1954. 달팽이 숫자

문제에서는 N을 입력받아 N*N 배열에 숫자를 시계방향으로 내부를 감싸듯이 출력해야만 한다.

삼성 SW Expert Academy에서 푼 문제 리스트 보기

github에서 코드 보기

문제 이해하기

문제는 다음 표를 보면 바로 이해가 가능하다.

배열의 크기를 입력받아 아래의 표처럼 숫자를 입력하여 출력하면 된다.

1

2

3

8

9

4

7

6

5

문제 풀이

점차 증가하는 숫자는 다음과 같은 경우에 방향을 변화시킨다. 변화하는 방향은 오른쪽- 아래 - 왼쪽 - 위(→·↓·←·↑) 순서이다.

- 다음에 숫자를 놓을 위치가 배열의 범위를 벗어 날 경우

- 다음에 숫자를 놓을 위치에 이미 숫자를 넣은 경우

방향을 변화시키면서  마지막 값(N*N) 숫자를 넣고 난 후 배열을 출력한다.

파이썬 코드

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
31
32
33
34
35
36
def solve(n):
    # right, down, left, up
    direction_list = [(0,1), (10), (0-1), (-10)]
    num = 0
    direction_index = 0
    current_r, current_c = 0-1
    array = [[-1]*for i in range(n)]
 
    while num < n*n:
        dir = direction_list[direction_index]
        temp_r = current_r + dir[0]
        temp_c = current_c + dir[1]
 
        # 범위 초과시 방향을 바꾼다
        if temp_c < 0 or temp_r < 0 or temp_c >= n or temp_r >= n or array[temp_r][temp_c] != -1:
            direction_index += 1
            if direction_index == 4:
                direction_index = 0
        else:
            num += 1
            current_r, current_c= temp_r, temp_c
            array[current_r][current_c] = num
 
    return array
 
 
if __name__ == "__main__":
    t = int(input())
    for c in range(t):
        n = int(input())
        print("#{0}".format(c+1))
        result = solve(n)
        for line in result:
            print(' '.join(map(str,line)))
 
 
cs

#SW Expert Academy #1954. 달팽이 숫자 #python 1954. 달팽이 숫자 #1954. 달팽이 숫자 python #파이썬 1954 #sw expert 1954. 달팽이 숫자