백준 - 1913번(달팽이)

최지홍·2022년 2월 5일
0

백준

목록 보기
20/145

문제 출처: https://www.acmicpc.net/problem/1913


문제

  • 홀수인 자연수 N이 주어지면, 다음과 같이 1부터 N2까지의 자연수를 달팽이 모양으로 N×N의 표에 채울 수 있다.
  • N이 주어졌을 때, 이러한 표를 출력하는 프로그램을 작성하시오. 또한 N2 이하의 자연수가 하나 주어졌을 때, 그 좌표도 함께 출력하시오. 예를 들어 N=5인 경우 6의 좌표는 (4,3)이다.

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

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        int N = Integer.parseInt(reader.readLine());
        int target = Integer.parseInt(reader.readLine());
        int[][] directions = {
                { -1, 0 },
                { 0, 1 },
                { 1, 0 },
                { 0, -1 },
        };

        int[][] matrix = new int[N][N];

        int direction = 0;
        int count = 1;
        int round = 0;
        int row = N / 2;
        int col = N / 2;
        int num = 1;

        while (num <= N * N) {
            for (int i = 0; i < count; i++) {
                matrix[row][col] = num++;
                row += directions[direction % 4][0];
                col += directions[direction % 4][1];
            }
            direction++; // 방향 벡터 변수 증가

            if (round++ > 0 && round % 2 == 0) {
                count++;
            }
        }

        int temp_x = 0;
        int temp_y = 0;

        for (int x = 0; x < N; x++) {
            for (int y = 0; y < N; y++) {
                sb.append(matrix[x][y]).append(" ");
                if (matrix[x][y] == target) {
                    temp_x = x;
                    temp_y = y;
                }
            }
            sb.append("\n");
        }
        sb.append(temp_x + 1).append(" ").append(temp_y + 1);

        System.out.println(sb);
    }

}

  • 로직을 생각해 볼 때, 진행 순서는 위, 오른쪽, 아래, 왼쪽이 순차적으로 반복된다.
  • 진행하며 같은 크기로 2번씩 진행된다.(1, 1, 2, 2, 3, 3, ...)
  • 여기서 1번은 해당 자리에 수를 넣고 다음 방향으로 좌표를 셋팅하는 것 까지이다.
profile
백엔드 개발자가 되자!

0개의 댓글