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

youngkyu MIn·2023년 10월 10일

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

class Solution {
    public int[][] solution(int n) {
        int[][] result = new int[n][n];

        int number = 1;
        int row = 0;
        int col = -1;
        int change = 1;

        while (n > 0) {

            for (int i = 0; i < n; i++) {
                col += change;
                result[row][col] = number;
                number++;
            }

            n--;

            for (int i = 0; i < n; i++) {
                row += change;
                result[row][col] = number;
                number++;
            }

            change *= -1;
        }

        return result;
    }
}

빙글뱅글빙글뱅글빙글뱅글빙글뱅글빙글뱅글빙글뱅글빙글뱅글빙글뱅글빙글뱅글빙글뱅글

profile
한 줄 소개

0개의 댓글