SWEA

SWEA 1954. 달팽이 숫자 Java

리콜 2023. 11. 5. 12:35

문제 링크 

https://swexpertacademy.com/main/code/problem/problemDetail.do?problemLevel=3&problemLevel=4&contestProbId=AV5PobmqAPoDFAUq&categoryId=AV5PobmqAPoDFAUq&categoryType=CODE&problemTitle=&orderBy=FIRST_REG_DATETIME&selectCodeLang=ALL&select-1=4&pageSize=10&pageIndex=1

 

SW Expert Academy

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

swexpertacademy.com

 

 

한바퀴 회전을 하나의 함수로 만들고

재귀(recursion)을 하여 풀었다.

생각은 했는데 상하좌우의 시작 좌표를 구하는데 너무 헷갈려서 시간이 걸렸다.

한번 재귀를 할때 마다 시작 좌표는 x+1,x+1이 되는데

해당 값을 이용하여 각 끝의 시작점을 가져올 수 있었다.

 

시작을 0,0 이 아니라 n+1배열을 만들어 1,1 부터 시작하였다면 좀 더 읽기 좋을 것 같다.(메모리를 적게 쓰고 싶었다...)

 

 

또한 주어지는 N이 짝수냐 홀수냐에 따라

홀수면 마지막에 제일 중간 좌표(회전의 중심?)에도 숫자를 넣어주어야 한다.

이를 여러가지 예를 만들며 확인해보니

홀수 일때 n/2를 하면 값이 나오는데 이를 x라 하였을때

x,x 좌표가 중앙이 되었다.

 

 

또한 출력에서 다른 문제와 다르게 각 테스트 케이스를 붙여서 출력해서 2번이나 수정하였다;;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Solution {


    static int n;
    static int[][] map;
    static int num = 1;
    public static void recur(int x, int y){
        if(n %2 == 0) {  //짝수일때
            if(x == n/2 +1){
                return;
            }
        }
        else{ //홀수 일때
            if(x == n /2){
                map[x][y] = num++;
                return;
            }
        }
        //우
        for(int i = y; i< n - y;i++){
            map[x][i] = num++;
        }

        //하
        for(int i = x +1 ; i < n - x; i++){
            map[i][n - 1 - y ] = num++;
        }
        //좌
        for(int i = n -2 -x; i>= y; i--){
            map[n-1-x][i]  = num++;
        }
        //상
        for(int i = n -2 -x; i > x;i--){
            map[i][y] = num++;
        }
        recur(x+1,y+1);

    }
    public static void main(String[] args) throws Exception {
        BufferedReader br =new BufferedReader(new InputStreamReader(System.in));

        int T = Integer.parseInt(br.readLine());

        for(int test_case = 1; test_case <= T; test_case++)
        {
            StringBuilder sb = new StringBuilder();
            n = Integer.parseInt(br.readLine());
            num = 1;
            map = new int[n][n];
            recur(0,0);
            sb.append("#").append(test_case).append("\n");
            for(int i = 0; i < n;i++){
                for(int j = 0; j<n;j++){
                    sb.append(map[i][j]).append(" ");
                }
                sb.append("\n");
            }
            System.out.print(sb);
        }
    }
}

 

반응형