๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ

[BOJ] 2606 ๋ฐ”์ด๋Ÿฌ์Šค [Java]

category Algorithm/BOJ 2022. 8. 25. 00:37

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

 

2606๋ฒˆ: ๋ฐ”์ด๋Ÿฌ์Šค

์ฒซ์งธ ์ค„์—๋Š” ์ปดํ“จํ„ฐ์˜ ์ˆ˜๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ปดํ“จํ„ฐ์˜ ์ˆ˜๋Š” 100 ์ดํ•˜์ด๊ณ  ๊ฐ ์ปดํ“จํ„ฐ์—๋Š” 1๋ฒˆ ๋ถ€ํ„ฐ ์ฐจ๋ก€๋Œ€๋กœ ๋ฒˆํ˜ธ๊ฐ€ ๋งค๊ฒจ์ง„๋‹ค. ๋‘˜์งธ ์ค„์—๋Š” ๋„คํŠธ์›Œํฌ ์ƒ์—์„œ ์ง์ ‘ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ๋Š” ์ปดํ“จํ„ฐ ์Œ์˜ ์ˆ˜๊ฐ€ ์ฃผ์–ด

www.acmicpc.net


1. ๋ฌธ์ œ ์š”์•ฝ

1๋ฒˆ์ด ๋ฐ”์ด๋Ÿฌ์Šค์— ๊ฑธ๋ฆฌ๋ฉด, 1๋ฒˆ๊ณผ ์—ฐ๊ฒฐ๋œ ๋ชจ๋“  ๋ฒˆํ˜ธ๊ฐ€ ๊ฐ์—ผ๋œ๋‹ค. 4๋ฒˆ๊ณผ 7๋ฒˆ์€ 1๋ฒˆ๊ณผ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ์ง€ ์•Š์œผ๋ฏ€๋กœ ๊ฐ์—ผ๋˜์ง€ ์•Š๋Š”๋‹ค.

์—ฐ๊ฒฐ ์ •๋ณด๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, 1๋ฒˆ์„ ์‹œ์ž‘์œผ๋กœ ๋ฐ”์ด๋Ÿฌ์Šค์— ๊ฐ์—ผ๋˜๋Š” ์ปดํ“จํ„ฐ์˜ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜๋ผ.

2. ํ’€์ด

๊ทธ๋ž˜ํ”„ ๋ฌธ์ œ์ด๋‹ค. ํ•ด๋‹น ๋…ธ๋“œ์— ์ธ์ ‘ํ•œ ๋…ธ๋“œ๋“ค์„ ๋”ฐ๋ผ ์—ฐ๊ฒฐ๋œ ๋ชจ๋“  ๋…ธ๋“œ๋“ค์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜๋ฉด ๋œ๋‹ค.

๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ๊ฐ€๊ธฐ ๋•Œ๋ฌธ์— DFS, BFS ๋ชจ๋‘ ๊ฐ€๋Šฅํ•˜๋‹ค. ํ•˜์ง€๋งŒ ์ธ์ ‘ํ•œ ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธํ•˜๊ธฐ๋งŒ ํ•˜๋ฉด ๋˜๊ธฐ ๋•Œ๋ฌธ์—

์ธ์ ‘ ๋…ธ๋“œ ๋ฐฉ๋ฌธ์— ํšจ์œจ์ ์ธ BFS๋ฅผ ์‚ฌ์šฉํ•˜์˜€๋‹ค. ์ „ํ˜•์ ์ธ BFS ํ‹€์„ ์‚ฌ์šฉํ•˜์˜€๋‹ค. 

๊ทธ๋ž˜ํ”„๋ฅผ ๊ตฌํ˜„ํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ์ธ์ ‘ ํ–‰๋ ฌ, ์ธ์ ‘ ๋ฆฌ์ŠคํŠธ๊ฐ€ ์žˆ๋‹ค. ๋‚˜๋Š” ์ธ์ ‘ ๋ฆฌ์ŠคํŠธ๋กœ ํ’€์–ด๋ณด์•˜๋‹ค.

 

 

3. ๋ฌธ์ œ์ 

์—ฌ๋Ÿฌ ๋ฐฉ๋ฒ•์œผ๋กœ ํ’€์–ด๋ณผ ๊ฒƒ

1. DFS

2. ์ธ์ ‘ํ–‰๋ ฌ

 

4. ์ฝ”๋“œ

BFS, ์ธ์ ‘๋ฆฌ์ŠคํŠธ

๋”๋ณด๊ธฐ

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.StringTokenizer;

public class BOJ_2606_๋ฐ”์ด๋Ÿฌ์Šค {

	static boolean[] visited;
	static List<List<Integer>> list = new ArrayList<> ();
	static int N, ans;
	static int cnt;
	public static void main(String[] args) throws Exception{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		N = Integer.parseInt(br.readLine());
		cnt = Integer.parseInt(br.readLine());
		visited = new boolean[N+1];
		
		for (int i = 0; i <= N; i++) {
			list.add(new ArrayList<>());
		}
		for (int i = 0; i < cnt; i++) {
			StringTokenizer st = new StringTokenizer(br.readLine());
			int num1 = Integer.parseInt(st.nextToken());
			int num2 = Integer.parseInt(st.nextToken());
			list.get(num1).add(num2); //์–‘๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„
			list.get(num2).add(num1);
		}
		
		bfs(1);
		System.out.println(ans);
	}
	static void bfs(int start) {
		Queue<Integer> queue = new ArrayDeque<>();
		queue.add(start);
		visited[start] = true;
		while (!queue.isEmpty()) {
			int front = queue.poll();
			int len = list.get(front).size();
			for (int i = 0; i < len; i++) {
				int next = list.get(front).get(i);
				if (visited[next]) continue;
				queue.add(next);
				ans++; //์ธ์ ‘ ๋…ธ๋“œ ๊ฐœ์ˆ˜ ์นด์šดํŠธ
				visited[next] = true;
			}
		}
		
	}
}