๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 1913_๋‹ฌํŒฝ์ด

๋ฟŒ์•ผ._. 2024. 7. 2. 14:15

Silver III

๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/1913)

< ๋‹ฌํŒฝ์ด >

 

๋ฌธ์ œ ํ’€์ด 

 

์ค‘๊ฐ„๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด์„œ ์ƒ, ์šฐ, ํ•˜, ์ขŒ ์ˆœ์œผ๋กœ ๋ฐฐ์—ด์„ ์ฑ„์šด๋‹ค. ์ด๋•Œ ์ด๋™ํ•˜๋Š” ์นธ ์ˆ˜๋Š” 1์นธ 2๋ฒˆ, 2์นธ 2๋ฒˆ, 3์นธ 2๋ฒˆ ์ด๋Ÿฐ ์‹์œผ๋กœ ์ด๋™ํ•œ๋‹ค.

 

 my solution (Java)

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

public class _1913_ { // ๋‹ฌํŒฝ์ด

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

		int n = Integer.parseInt(bf.readLine());
		int m = Integer.parseInt(bf.readLine());

		int arr[][] = new int[n][n];
		int resultX = (n / 2) + 1, resultY = (n / 2) + 1, idx = 1, turn = 1;

		int dx[] = { -1, 0, 1, 0 };
		int dy[] = { 0, 1, 0, -1 };

		int x = n / 2, y = n / 2, dir = 0;
		arr[x][y] = idx++;
		while (idx <= n * n) {
			for (int j = 0; j < 2; j++) {
				for (int i = 0; i < turn; i++) {
					x += dx[dir];
					y += dy[dir];
					arr[x][y] = idx++;
					if (idx == m + 1) {
						resultX = x + 1;
						resultY = y + 1;
					}
					if (idx > n * n) {
						break;
					}
				}
				dir += 1;
				if (dir == 4) {
					dir = 0;
				}
				if (idx > n * n) {
					break;
				}
			}
			turn += 1;
		}

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				bw.write(arr[i][j] + " ");
			}
			bw.write("\n");
		}
		bw.write(resultX + " " + resultY);
		bw.flush();
	}
}
๋ณ€์ˆ˜)
n, m : ํ™€์ˆ˜์ธ ์ž์—ฐ์ˆ˜, N*N ์ดํ•˜์˜ ์ž์—ฐ์ˆ˜
arr : N*N ํ‘œ
resultX, resultY : ์œ„์น˜๋ฅผ ์ฐพ๊ณ ์ž ํ•˜๋Š” N*N ์ดํ•˜์˜ ์ž์—ฐ์ˆ˜์˜ ์œ„์น˜
idx : ํ˜„์žฌ ๊ฐ’
turn : ์ด๋™ ์นธ ์ˆ˜
dx, dy : ์ƒ, ์šฐ, ํ•˜, ์ขŒ
x, y : ํ˜„์žฌ ์œ„์น˜
dir : ๋ฐฉํ–ฅ

 

ํ™€์ˆ˜์ธ ์ž์—ฐ์ˆ˜์™€ ์œ„์น˜๋ฅผ ์ฐพ๊ณ ์ž ํ•˜๋Š” ๊ฐ’์„ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค. idx๊ฐ€ n*n ์ดํ•˜์ผ ๋•Œ ๋‹ค์Œ ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•œ๋‹ค.

 

1) 2๋ฒˆ์”ฉ 2) ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•œ ํ›„ ๋ฐฉํ–ฅ์„ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค. idx๊ฐ’์ด n*n๋ณด๋‹ค ํฌ๋‹ค๋ฉด ์ข…๋ฃŒํ•œ๋‹ค.

2) turn ์ˆ˜๋งŒํผ ํ˜„์žฌ ๋ฐฉํ–ฅ๋Œ€๋กœ ์ด๋™ํ•œ ํ›„ idx๊ฐ’์„ ์ €์žฅํ•œ๋‹ค. ๋งŒ์•ฝ idx๊ฐ’์ด ์ฐพ์œผ๋ ค๋Š” ์ˆ˜๋ผ๋ฉด ์œ„์น˜๋ฅผ resultX์™€ resultY์— ์ €์žฅํ•œ๋‹ค. idx๊ฐ’์ด n*n๋ณด๋‹ค ํฌ๋‹ค๋ฉด ์ข…๋ฃŒํ•œ๋‹ค.

3) turn ์ฆ๊ฐ€

 

arr ๋ฐฐ์—ด์„ ์ถœ๋ ฅํ•œ ํ›„ resultX์™€ resultY๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 

* ๊ฐ’์„ ์ดˆ๊ธฐํ™”ํ•  ๋•Œ ์ž˜ ๊ณ ๋ คํ•ด์•ผ ํ•œ๋‹ค.