본문 바로가기
Programmers

[프로그래머스]정수를 나선형으로 배치하기 feat 2차원 배열 선언하여 풀기

by 딸기뚜왈기 2024. 1. 22.

 

 

def solution(n):
    arr = [[0] * n  for i in range(n)] 
    #2차원 배열 선언하기 많이 나옴. #이거는 종이에 써서 암기.
    a = 0
    b = 0
    x, y = 0,0
    
    moving = [[0,1],[1,0],[0,-1],[-1,0]]
    for i in range(1, n**2+1):
        arr[x][y] = i
    
        if (x+moving[b][0]) >= n or (y+moving[b][1]) >= n or (y+moving[b][1]) < 0 or (x+moving[b][0]) < 0 or arr[x+moving[b][0]][y+moving[b][1]] != 0:
        
            b = (b + 1)%(len(moving))
        x += moving[b][0]
        y += moving[b][1]
    return arr
def solution(n):
    dy = [0, 1, 0, -1]
    dx = [1, 0, -1, 0]
    y, x = 0, -1

    arr = [[0] * n for _ in range(n)]
    cnt = 1
    direction = 0
    while cnt <= n**2:
        ny, nx = y + dy[direction], x + dx[direction]
        if 0 <= ny < n and 0 <= nx < n and not arr[ny][nx]:
            arr[ny][nx] = cnt
            cnt += 1
            y, x = ny, nx
        else:
            direction = (direction + 1) % 4

    return arr