Muscardinus

삼각달팽이 본문

알고리즘 문제/[프로그래머스] Lv2

삼각달팽이

Muscardinus 2021. 2. 1. 23:12
728x90

programmers.co.kr/learn/courses/30/lessons/68645

 

코딩테스트 연습 - 삼각 달팽이

5 [1,2,12,3,13,11,4,14,15,10,5,6,7,8,9] 6 [1,2,15,3,16,14,4,17,21,13,5,18,19,20,12,6,7,8,9,10,11]

programmers.co.kr

function solution(n) {
    var answer = [];
    for (let i = 1; i <= n; i++) answer.push(Array.from({length: i}, () => 0));
    let num = 1;
    let cnt = 0;
    let startColumn = 0;
    let startRow = 0;
    let endColumn = n - 1;
    let endRow = n - 1;
    while (startColumn <= endColumn && startRow <= endRow) {
        for (let i = startRow; i <= endRow; i++) {
            answer[i][startColumn] = num;
            num++;
        }
        startRow++;
        startColumn++;
        for (let i = startColumn; i <= endColumn; i++) {
            answer[endRow][i] = num;
            num++;
        }
        endRow--;
        endColumn--;
        for (let i = endRow; i >= startRow; i--) {
            answer[i][answer[i].length - 1 - cnt] = num;
            num++;
        }
        endColumn--;
        startRow++;
        cnt++;
    }
    return answer.flat();
}
728x90
Comments