๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜/๋ฌธ์ œ

[์ž๋ฐ”] ๋ฐฑ์ค€ 2606 - ๋ฐ”์ด๋Ÿฌ์Šค

by applemango2021 2020. 12. 5.

์–ด๋ ค์šด ๋ฌธ์ œ๋„ ์ด๋ ‡๊ฒŒ ์‰ฝ๊ฒŒ ํ’€๋ ธ์œผ๋ฉด ์ข‹๊ฒ ๋‹ค ํ•˜ํ•˜ํ•˜ํ•˜ํ•˜

 

ArrayList ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด์„œ BFS๋กœ ํ’€์—ˆ๋‹ค.

Queue์—๋‹ค๊ฐ€ 1์ด๋ž‘ ์ด์–ด์ง„ ์ปดํ“จํ„ฐ๋“ค ๋ฒˆํ˜ธ ๋„ฃ๊ณ , infected ์—ฌ๋ถ€ ์ฒดํฌํ•ด์„œ infected=false์ธ ์ปดํ“จํ„ฐ๋“ค๋งŒ ๋‹ค์‹œ ํ์—๋‹ค๊ฐ€ ์ง‘์–ด ๋„ฃ์–ด์คฌ๋‹ค. ์ด๋ฏธ ๊ฐ์—ผ ํ™•์ธ๋œ ์ปดํ“จํ„ฐ๋ผ๋ฉด ๊ฐ์—ผ์„ ํ™•์ธํ•œ ์‹œ์ ์— ์—ฐ๊ฒฐ๋œ ์ปดํ“จํ„ฐ๋“ค์„ ๋‹ค ํ์—๋‹ค๊ฐ€ ๋„ฃ์–ด์คฌ์„ ํ…Œ๋‹ˆ๊นŒ!

 

N์˜ ๋ฒ”์œ„๊ฐ€ ์ž‘์•„์„œ ์ธ์ ‘ ๋ฆฌ์ŠคํŠธ ๋Œ€์‹ ์— N+1 x N+1 ํ–‰๋ ฌ์„ ๋งŒ๋“ค์–ด์„œ ์ฒดํฌํ–ˆ์–ด๋„ ๋์„ ๊ฒƒ ๊ฐ™๋‹ค.

์Œ ์˜ˆ๋ฅผ ๋“ค์–ด, network[A][B] = 1 = network[B]=[A] ์ด๋Ÿฐ ์‹์œผ๋กœ?

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;

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

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int N = Integer.parseInt(br.readLine().trim());
		int M = Integer.parseInt(br.readLine().trim());
		
		ArrayList<Integer>[] network = new ArrayList[N+1];
		for(int n=1;n<=N;n++) {
			network[n] = new ArrayList<Integer>();
		}
		
		String[] str;
		int A,B;
		for(int m=1;m<=M;m++) {
			str = br.readLine().trim().split(" ");
			
			A = Integer.parseInt(str[0]);
			B = Integer.parseInt(str[1]);
			
			network[A].add(B);
			network[B].add(A);
		}
	
		boolean[] infected = new boolean[N+1];
		Queue<Integer> que = new LinkedList<Integer>();
		que.add(1);
		infected[1] = true;
		int cnt = 0;
		
		int now;
		while(!que.isEmpty()) {
			now = que.poll();

			ArrayList<Integer> connected = new ArrayList<Integer>();
			connected = network[now];
			for (Integer i : connected) {
				if(!infected[i]) {
					infected[i] = true;
					cnt++;
					que.add(i);
				}
			}
		}
		System.out.println(cnt);
	}
}