문제
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
문제 설명
문제 풀이
BFS 알고리즘을 통해 해당 노드와 친구인 노드들을 큐에 추가하고 단계를 거칠 때마다 가중치를 하나씩 증가한다.
코드
import java.util.*;
import java.io.*;
class Main {
static int minSum = Integer.MAX_VALUE;
static int result = 5001;
static ArrayList<ArrayList<Integer>> gph = new ArrayList<>();
static int N;
static void BFS(int node) {
Queue<Integer> q = new LinkedList<>();
int sum = 0;
int[] visit = new int[5001];
q.offer(node);
visit[node] = 1;
while(!q.isEmpty()) {
int base = q.poll();
ArrayList<Integer> neighbor = gph.get(base);
for(int i : neighbor) {
if(visit[i] == 0) {
q.offer(i);
if(base == node)
visit[i] = visit[base];
else
visit[i] = visit[base] + 1;
}
}
}
for(int i = 1; i <= N; i++) {
sum += visit[i];
}
if(sum < minSum) {
minSum = sum;
result = node;
}
else if (sum == minSum)
result = result < node ? result : node;
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
for(int i = 0; i <= N; i++) {
gph.add(new ArrayList<>());
}
for(int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
int A = Integer.parseInt(st.nextToken());
int B = Integer.parseInt(st.nextToken());
gph.get(A).add(B);
gph.get(B).add(A);
}
for(int i = 1; i <= N; i++) {
BFS(i);
}
System.out.println(result);
}
}
'🧑💻코딩 테스트 > 백준 (BOJ)' 카테고리의 다른 글
[코딩테스트/백준 알고리즘] 16928번 - 뱀과 사다리 게임 (0) | 2023.05.15 |
---|---|
[코딩테스트/백준 알고리즘] 1074번 - Z (Java, 자바 풀이) (0) | 2023.01.18 |
[코딩테스트/백준 알고리즘] 1992번 - 쿼드트리 (Java, 자바 풀이) (0) | 2023.01.06 |
[코딩테스트/ 백준 알고리즘] 17626번 - Four Squares (Java, 자바 풀이) (0) | 2023.01.05 |
[코딩테스트/백준 알고리즘] 7576번 - 토마토 (Java, 자바 풀이) (0) | 2022.12.30 |
댓글