[プログラマー]カタツムリ(Python)


質問する


カタツムリ匹

問題の説明


この問題では,数字はそれぞれ下,右,対角線に増加し,三角形を描くときにさらに下に移動して増加する.これは無限に繰り返され、最終数字が1~Nの和のNX(N+1)/2のときに終了する.
  • は所定の方向に移動する.
  • が移動した座標が範囲を超えているか、すでに数字がある場合は、方向を変更します.
  • でない場合、現在の数値+1の値は現在の座標に格納されます.
  • ソースコード

    def solution(n):
        answer = []
        arr = [[0] * i for i in range(1, n + 1)]
        x, y = -1, 0  # 현재 좌표
        dx = [1, 0, -1]  # 각각 아래, 오른쪽, 대각선으로 이동
        dy = [0, 1, -1]
        direct = 0  # 방향
        now = 0  # 현재 숫자
        while now < n * (n + 1) // 2:
            nx = x + dx[direct]
            ny = y + dy[direct]
            # 끝에 도달 혹은 숫자가 있음 -> 방향 전환
            if direct == 0 and (nx >= n or arr[nx][ny] > 0):
                direct = 1
                continue
            elif direct == 1 and (ny >= n or arr[nx][ny] > 0):
                direct = 2
                continue
            elif direct == 2 and arr[nx][ny] > 0:
                direct = 0
                continue
    
            now += 1
            arr[nx][ny] = now
            x = nx
            y = ny
        for x in arr:
            answer.extend(x)
        return answer