코딩테스트

[이차원 배열] SW Expert academy 1954. 달팽이 숫자

Enhydra lutris 2025. 5. 13. 17:39
728x90

 

문제

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5PobmqAPoDFAUq

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

 

풀이

두가지 요소를 캐치하면 되는 문제였습니다.

1. 방향은 오른쪽->아래->왼쪽->위로 반복된다.

2. 방향이 아래가 될때와 위가 될때 해당 방향으로 움직이는 횟수가 1번씩 줄어든다.

코드


import java.util.Scanner;
import java.io.FileInputStream;

class Solution
{
    public static void main(String args[]) throws Exception
    {
        Scanner sc = new Scanner(System.in);
        int T;
        T=sc.nextInt();

        for(int test_case = 1; test_case <= T; test_case++)
        {
            int N = sc.nextInt();
            int[][] arr = new int[N][N];
            int count = N;         // 한 방향당 몇 칸을 갈지
            int type = 0;          // 방향 (0: 오른쪽, 1: 아래, 2: 왼쪽, 3: 위)
            int x = -1, y = 0;      // 현재 위치
            int num = 1;


            while (count > 0) {
                for (int i = 0; i < count; i++) {
                    if (type == 0) x++;          // 오른쪽
                    else if (type == 1) y++;     // 아래
                    else if (type == 2) x--;     // 왼쪽
                    else if (type == 3) y--;     // 위
                    arr[y][x] = num++;
                }

                type = (type + 1) % 4; // 다음 방향으로 바꾸기
                if (type == 1 || type == 3) count--;
            }

            // 출력
            System.out.println("#" + (t + 1));
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < N; j++) {
                    System.out.print(arr[i][j] + " ");
                }
                System.out.println();
            }


        }
    }
}

 

 

헷갈렸던 포인트들

거의 2년만에 코테 문제를 풀다보니 알고리즘적인 요소보다는 아래와 같은 포인트들이 헷갈렸습니다..ㅎㅎ

  1. arr[y][x] vs arr[x][y]
    • 대부분의 2차원 배열은 arr[행][열], 즉 arr[y][x] 구조입니다.
    • 그런데 수학적 좌표계나 (x, y)로 익숙한 경우 → arr[x][y]로 잘못 쓸 수 있습니다.
  2. 초기 좌표 설정 (x = -1, y = 0)
    • 달팽이 배열처럼 이동 기반 문제에서는 시작점을 -1로 설정하는 트릭이 자주 사용됨