๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 9400_Calculate the Fence Needed

๋ฟŒ์•ผ._. 2025. 7. 21. 14:17
๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/9400)

< Calculate the Fence Needed >

 

๋ฌธ์ œ ํ’€์ด 

 

ํ•œ ๊ฒฉ์ž ์นธ์— ํ•„์š”ํ•œ ์šธํƒ€๋ฆฌ์˜ ๊ธธ์ด = 4 - (๋†์žฅ์˜ ํ•œ ๊ฒฉ์ž ์นธ๊ณผ ์—ฐ๊ฒฐ๋œ ๋†์žฅ์˜ ๊ฒฉ์ž ์นธ์˜ ์ˆ˜)

 

my solution (Java)

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class _9400_ { // Calculate the Fence Needed

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

		int N = 0;
		Queue<int[]> queue = new LinkedList<>();

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

		while ((N = Integer.parseInt(bf.readLine())) != 0) {
			boolean arr[][] = new boolean[101][101];

			for (int i = 0; i < N; i++) {
				st = new StringTokenizer(bf.readLine());

				int x = Integer.parseInt(st.nextToken());
				int y = Integer.parseInt(st.nextToken());

				arr[101 - x][y] = true;
				queue.add(new int[] { 101 - x, y });
			}

			int result = 0;
			while (!queue.isEmpty()) {
				int temp[] = queue.poll();
				int cnt = 0;

				for (int i = 0; i < 4; i++) {
					int x = temp[0] + dx[i];
					int y = temp[1] + dy[i];

					if (x >= 0 && x < 101 && y >= 0 && y < 101 && arr[x][y]) {
						cnt += 1;
					}
				}
				result += (4 - cnt);
			}
			bw.write(result + "\n");
		}
		bw.flush();
	}
}
๋ณ€์ˆ˜)
N : ๋†์žฅ ๋ฉด์ 
queue : Queue <int []>
dx, dy : ์ƒ, ํ•˜, ์ขŒ, ์šฐ
arr : ๋†์žฅ
result : ํ•„์š”ํ•œ ์šธํƒ€๋ฆฌ ๊ธธ์ด
cnt : ๋†์žฅ์˜ ํ•œ ๊ฒฉ์ž ์นธ๊ณผ ์—ฐ๊ฒฐ๋œ ๋†์žฅ์˜ ๊ฒฉ์ž ์นธ์˜ ์ˆ˜

 

๋†์žฅ ๋ฉด์ ์„ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค. ๋†์žฅ ๋ฉด์ ๋งŒํผ ์ขŒํ‘œ๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ๋ฐฐ์—ด arr์— ํ‘œ์‹œํ•˜๊ณ  queue์— ์ €์žฅํ•œ๋‹ค. queue๊ฐ€ ๋นŒ ๋•Œ๊นŒ์ง€ ๋‹ค์Œ ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•œ๋‹ค.

 

1) queue poll

2) ์ƒ, ํ•˜, ์ขŒ, ์šฐ๋ฅผ ํƒ์ƒ‰ํ•˜๋ฉฐ ๋†์žฅ์ธ์ง€ ํ™•์ธ

3) ํ•„์š”ํ•œ ์šธํƒ€๋ฆฌ ๊ธธ์ด์— (4- ๋†์žฅ์˜ ํ•œ ๊ฒฉ์ž ์นธ๊ณผ ์—ฐ๊ฒฐ๋œ ๋†์žฅ์˜ ๊ฒฉ์ž ์นธ์˜ ์ˆ˜) ๋”ํ•˜๊ธฐ

 

์ตœ์ข… result๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.



 

'๐ŸŒžAlgorithm > ๐Ÿ”ฅBaekjoon' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Baekjoon] 15426_GlitchBot  (3) 2025.07.23
[Baekjoon] 30949_Equal Schedules  (2) 2025.07.22
[Baekjoon] 4466_A Smart Brain is a Tasty Brain  (3) 2025.07.18
[Baekjoon] 17585_Circuit Math  (2) 2025.07.17
[Baekjoon] 8594_Program  (0) 2025.07.16