[プログラマー]カタツムリ(Python)
質問する
カタツムリ匹
問題の説明
この問題では,数字はそれぞれ下,右,対角線に増加し,三角形を描くときにさらに下に移動して増加する.これは無限に繰り返され、最終数字が1~Nの和のNX(N+1)/2のときに終了する.
ソースコード
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
Reference
この問題について([プログラマー]カタツムリ(Python)), 我々は、より多くの情報をここで見つけました https://velog.io/@qweadzs/프로그래머스-삼각-달팽이Pythonテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol