[SWEA] 1954. 달팽이 숫자
728x90

문제

  • 1차 접근 방법
  • 정답 여부

1차 접근 방법

방향을 잘 조절해서 2차원 배열 안에 1 ~ (N * N + 1)을 넣어주자.

T = int(input())
for test_case in range(1, T + 1):
    N = int(input())
    print(f'#{test_case}')

    answer = [[0] * N for _ in range(N)]

    directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
    direction_index = 0

    x, y = 0, 0  # 시작 위치
    for i in range(1, N * N + 1):
        answer[x][y] = i  
        next_x, next_y = x + directions[direction_index][0], y + directions[direction_index][1]

        if not (0 <= next_x < N and 0 <= next_y < N and answer[next_x][next_y] == 0): # 방문했거나 0 ~ N-1 범위 넘어갔을 경우에 방향 전환
            direction_index = (direction_index + 1) % 4 
            next_x, next_y = x + directions[direction_index][0], y + directions[direction_index][1]

        x, y = next_x, next_y

    for row in answer:
        print(' '.join(map(str, row)))

정답 여부

  • 정답!
  • direction_index = (direction_index + 1) % 4 이 부분이 헷갈려서 헤맸다...
728x90
반응형