본문 바로가기
CODING/Python

[파이썬:Python]달팽이배열

by NOBLESSE 2020. 7. 4.
728x90
반응형

좌에서 우, 우에서 좌, 위에서 아래, 아래에서 위 총 네 가지로 분류하여 달팽이 배열을 만들게끔 해봤습니다.
기존에 많이 풀이되는 방식보다 이해하기 쉬워 처음 코딩을 배우는 분들께 도움이 될까해서 업로드해봅니다.

a = int(input("n값을 입력하시오."))

result=[[0]*a for i in range(a)]

n=1

ab = 0
ba = 0

checked = 1

while True:
    if n == (a*a)+1:
        break
    
    if checked % 5 == 1:
        for o in range(a):
            if result[ab][o] == 0:
                result[ab][o] = n
                n += 1
        
    if checked % 5 == 2:
        for i in range(a):
            if result[i][a-1-ab] == 0:
                result[i][a-1-ab] = n
                n += 1
        ab += 1

    if checked % 5 == 3:
        for o in range(a):
            if result[a-1-ba][a-1-o] == 0:
                result[a-1-ba][a-1-o] = n
                n += 1
                
    if checked % 5 == 4:
        for i in range(a):
            if result[a-1-i][ba] == 0:
                result[a-1-i][ba] = n
                n += 1
        ba += 1
                
    if o % (a-1) == 0 and o != 0:
            checked += 1
                
    if checked == 5:
            checked = 1
        
for i in result:
    print(i)

 

728x90
반응형