코딩 테스트 (Java)/코딩 기초 트레이닝 (프로그래머스)

181832. 정수를 나선형으로 배치하기

가지코딩 2025. 4. 23. 10:23

https://school.programmers.co.kr/learn/courses/30/lessons/181832

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr


문제

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

 

제한사항

  • 1 ≤ n ≤ 30

 

입출력 예

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

 

입출력 예 #1

  • 예제 1번의 n의 값은 4로 4 × 4 배열에 다음과 같이 1부터 16까지 숫자를 채울 수 있습니다.
행 \ 열 0 1 2 3
0 1 2 3 4
1 12 13 14 5
2 11 16 15 6
3 10 9 8 7
따라서 [[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]를 return 합니다.

 

입출력 예 #2

  • 예제 2번의 n의 값은 5로 5 × 5 배열에 다음과 같이 1부터 25까지 숫자를 채울 수 있습니다.
행 \ 열 0 1 2 3 4
0 1 2 3 4 5
1 16 17 18 19 6
2 15 24 25 20 7
3 14 23 22 21 8
4 13 12 11 10 9
따라서 [[1, 2, 3, 4, 5], [16, 17, 18, 19, 6], [15, 24, 25, 20, 7], [14, 23, 22, 21, 8], [13, 12, 11, 10, 9]]를 return 합니다.

풀이

class Solution {
    public int[][] solution(int n) {
        int[][] arr = new int[n][n];
        int k = 1;

        int top = 0, bottom = n - 1, left = 0, right = n - 1;

        while (top <= bottom && left <= right) {
            for (int i = left; i <= right; i++){
                arr[top][i] = k++;
            }
            top++;

            for (int i = top; i <= bottom; i++) {
                arr[i][right] = k++;
            }
            right--;

            if (top <= bottom) {
                for (int i = right; i >= left; i--){
                    arr[bottom][i] = k++;
                }
                bottom--;
            }

            if (left <= right) {
                for (int i = bottom; i >= top; i--){
                    arr[i][left] = k++;
                }
                left++;
            }
        }

        return arr;
    }
}

 

 

 


GitHub: https://github.com/gajicoding/coding_test/edit/main/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4/0/181832.%E2%80%85%EC%A0%95%EC%88%98%EB%A5%BC%E2%80%85%EB%82%98%EC%84%A0%ED%98%95%EC%9C%BC%EB%A1%9C%E2%80%85%EB%B0%B0%EC%B9%98%ED%95%98%EA%B8%B0

 

coding_test/프로그래머스/0/181832. 정수를 나선형으로 배치하기 at main · gajicoding/coding_test

This is an auto push repository for Baekjoon Online Judge created with [BaekjoonHub](https://github.com/BaekjoonHub/BaekjoonHub). - gajicoding/coding_test

github.com


출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges

 

코딩테스트 연습 | 프로그래머스 스쿨

개발자 취업의 필수 관문 코딩테스트를 철저하게 연습하고 대비할 수 있는 문제를 총망라! 프로그래머스에서 선발한 문제로 유형을 파악하고 실력을 업그레이드해 보세요!

school.programmers.co.kr