[백준] 5567번 결혼식 (bfs, 구현 )

728x90
반응형

www.acmicpc.net/problem/5567

 

5567번: 결혼식

2와 3은 상근이의 친구이다. 또, 3과 4는 친구이기 때문에, 4는 상근이의 친구의 친구이다. 5와 6은 친구도 아니고, 친구의 친구도 아니다. 따라서 2,3,4 3명의 친구를 결혼식에 초대한다.

www.acmicpc.net

처음에 네트워크를 구하는 줄알고 dfs인 줄 알았으나 depth (친구의 친구)가 2인 곳까지만 탐색하므로 

bfs로 풀었다.

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
	static int n,m;
	static ArrayList<Integer>[] friend;
	static boolean[] vis;
	static int answer;
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		n=sc.nextInt();
		m=sc.nextInt();
		friend=new ArrayList[n+1];
		vis=new boolean[n+1];
		for (int i = 1; i <=n; i++) {
			friend[i]=new ArrayList<>();
		}
		for (int i = 0; i <m; i++) {
			int a=sc.nextInt();
			int b=sc.nextInt();
			friend[a].add(b);
			friend[b].add(a);
		}
		Queue<Integer> q=new LinkedList<Integer>();
		q.add(1);
		vis[1]=true;
		int depth=0;
		while(q.size()!=0) {
			int len=q.size();
			if(depth==2)break;
			for (int i = 0; i < len; i++) {
				int cur=q.poll();
				for (int k = 0; k < friend[cur].size(); k++) {
					int next=friend[cur].get(k);
					if(vis[next])continue;
					vis[next]=true;
					answer+=1;
					q.add(next);
				}
			}
			depth++;
		}
		
	
		System.out.println(answer);
	}

}
728x90
반응형
TAGS.

Comments