코딩테스트

[JAVA] 백준 좌석 10157_배정 시뮬레이션

coding dew 2025. 2. 11. 23:21

[문제링크]

https://www.acmicpc.net/problem/10157

📌 정답 코드

import java.util.Scanner;

public class SpiralSeating {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int C = sc.nextInt(); 
        int R = sc.nextInt();
        int K = sc.nextInt(); 
        
        if (K > C * R) {
            System.out.println(0);
            return;
        }
        int[] dx = {0, 1, 0, -1};
        int[] dy = {1, 0, -1, 0};
        int[][] seats = new int[R][C]; 
        int x = 0, y = 0, direction = 0;
        
        for (int num = 1; num <= K; num++) {
            seats[y][x] = num;
            
            if (num == K) { // K번째 사람의 좌석 찾음
                System.out.println((x + 1) + " " + (y + 1));
                return;
            }
            int nx = x + dx[direction];
            int ny = y + dy[direction];
            
            // 경계를 넘거나 이미 차 있으면 방향 전환
            if (nx < 0 || nx >= C || ny < 0 || ny >= R || seats[ny][nx] != 0) {
                direction = (direction + 1) % 4; // 방향 변경
                nx = x + dx[direction];
                ny = y + dy[direction];
            }
            x = nx;
            y = ny;
        }
    }
}