프로그래머스 - 정수를 나선형으로 배치하기

Lellow_Mellow·2023년 6월 10일
1
post-thumbnail

✨ Lv. 0 - 정수를 나선형으로 배치하기

문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/181832

문제 설명

양의 정수 n이 매개변수로 주어집니다. n × n 배열에 1부터 n^2 까지 정수를 인덱스 [0][0]부터 시계방향 나선형으로 배치한 이차원 배열을 return 하는 solution 함수를 작성해 주세요.


제한사항

  • 1 ≤ n ≤ 30

풀이 코드 + 설명

오른쪽 > 아래 > 왼쪽 > 위 방향을 반복하며 배열의 범위를 벗어나거나 이미 숫자가 지정된 칸이라면 방향을 바꾸어 숫자를 지정해주는 방식을 반복하면 됩니다.

function solution(n) {
    let result = Array.from({length: n}, (_) => new Array(n).fill(0));
    let counter = 1, i = 0, j = 0, direction = 0;
    while(counter !== n * n + 1) {
        result[i][j] = counter;
        counter++;
        
        if(direction === 0) {
            if(j + 1 === n || result[i][j + 1] !== 0) {
                direction = 1;
                i++;
            }
            else j++;
        }
        else if(direction === 1) {
            if(i + 1 === n || result[i + 1][j] !== 0) {
                direction = 2;
                j--;
            }
            else i++;
        }
        else if(direction === 2) {
            if(j - 1 === -1 || result[i][j - 1] !== 0) {
                direction = 3;
                i--;
            }
            else j--;
        }
        else {
            if(i - 1 === -1 || result[i - 1][j] !== 0) {
                direction = 0;
                j++;
            }
            else i--;
        }
        
    }
    return result;
}

첫 풀이 코드는 이와 같이 각 케이스에 대하여 하나씩 처리하였습니다. 이 과정을 아래와 같이 간결하게 작성할 수 있습니다. 각 방향마다 i, j의 증감을 담고 있는 direction을 선언한 후, 나머지 연산을 이용해서 현재의 방향에 따라 i, j의 값을 정해줍니다.

범위를 벗어나거나 값이 이미 존재하는 경우에는 방향을 바꾸어 i, j를 지정해줍니다.

function solution(n) {
    const direction = [[0, 1], [1, 0], [0, -1], [-1, 0]];
    let result = Array.from({length: n}, (_) => new Array(n).fill(0));
    let i = 0, j = 0, current = 0;
    for(let counter = 1; counter <= n * n; counter++) {
        result[i][j] = counter;
        let curI = i + direction[current][0];
        let curJ = j + direction[current][1];
        if(curI >= n || curJ >= n || curI < 0 || curJ < 0 || result[curI][curJ] !== 0) {
            current = (current + 1) % 4;
            curI = i + direction[current][0];
            curJ = j + direction[current][1];
        }
        i = curI;
        j = curJ;
    }
    return result;
}

profile
잔잔한 물결에서 파도로, 도약을 위한 도전. 함께하는 성장

0개의 댓글