ALGORITHM/프로그래머스 | 백준 | 삼성 | 카카오

[백준] 1389번 케빈 베이컨의 6단계 법칙

SZCODE 2020. 8. 3. 20:09

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

 

1389번: 케빈 베이컨의 6단계 법칙

첫째 줄에 유저의 수 N (2 ≤ N ≤ 100)과 친구 관계의 수 M (1 ≤ M ≤ 5,000)이 주어진다. 둘째 줄부터 M개의 줄에는 친구 관계가 주어진다. 친구 관계는 A와 B로 이루어져 있으며, A와 B가 친구라는 뜻��

www.acmicpc.net

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

public class Main {
	static int N, M;
	static int[][] map;
	static boolean[] visited;
	static Queue<Integer> queue;
	static int count = 0, answer = 1, total = 0, min = Integer.MAX_VALUE;
	static int[] check;
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		N = sc.nextInt();
		M = sc.nextInt();
		map = new int[N + 1][N + 1];
		queue = new LinkedList();
		
		for (int i = 0; i < M; i++) {
			int a = sc.nextInt();
			int b = sc.nextInt();
			map[a][b] = 1;
			map[b][a] = 1;
		} // end of input

		for (int i = 1; i < N + 1; i++) {
			visited = new boolean[N + 1];
			check = new int[N+1];
			total = 0;
			
			bfs(i);
			if(total<min) {
				min = total;
				answer = i;
			}
		}
		
			
		System.out.println(answer);
		
	
	}

	public static void bfs(int i) {
		
		count = 0;
		queue.offer(i);
		visited[i] = true;
		
		while (!queue.isEmpty()) {
			int len = queue.size();
			count++;
			for (int l = 0; l < len; l++) {
				int nv = queue.poll();
				
				for (int j = 1; j < N + 1; j++) {
					if (map[nv][j] == 1 && !visited[j]) {
						queue.offer(j);
						visited[j] = true;
						total += count;
					}
				}
			}
			
		}
		
	}
}