Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 1012 자바
- 1697 자바
- 백준 5430자바
- 5430자바
- 1389 JAVA
- 알고리즘
- ubuntu
- 백준
- 백준 1012 java
- 1012 java
- 노트북 서버
- 퇴사
- 백준 1012 자바
- 자바
- React Native
- 5430 java
- BFS
- Ubuntu USB부팅
- mobaXTerm
- 백준 2615
- Expo
- 백준 유기농 배추
- 백준 1389 자바
- 1389자바
- 백준 1697 자바
Archives
- Today
- Total
삽질메모장
백준 1389번 : 케빈 베이컨의 6단계 법칙(java) 본문
문제
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
난이도 : 실버 1
유형 : 그래프, BFS, 플로이드 - 위셜
접근법
핵심은 각각의 노드에서 모든 노드를 탐색하는 최단경로를 구하며 새로운 노드 방문시마다 값을 누적하면 된다.
그래프는 ArrayList<Integer>[모든 노드] 로 선언하고 각 노드의 간선을 양방향으로 입력하고 BFS를 돌렸다.
풀이
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class BOJ1389 {
static StringBuilder sb = new StringBuilder();
static ArrayList<Integer>[] graph;
static int[] check;
static int N, M;
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(bf.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
check = new int[N+1];
graph = new ArrayList[N+1];
for(int i=1; i<=N; i++){
graph[i] = new ArrayList<>();
}
for(int i=1; i<=M; i++){
st = new StringTokenizer(bf.readLine());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
graph[x].add(y);//양방향
graph[y].add(x);//양방향
}
int MinValue=Integer.MAX_VALUE;
int MinIndex =0;
for(int i =1; i<=N; i++){
int unitMinValue = bfs(i);
if(MinValue > unitMinValue){ //어차피 index 가 낮은것부터 진행 되므로 동점은 고려 필요 x
MinValue = unitMinValue;
MinIndex =i;
}
}
System.out.println(MinIndex);
}
static int bfs(int start){
Arrays.fill(check, -1);
Queue<Integer> qu = new LinkedList<>();
qu.add(start);
int cnt =0;
check[start]=0;
while (!qu.isEmpty()){
int x = qu.poll();
for (int y : graph[x]){ //현재 노드에서 방문가능한 모든 노드 방문
if (check[y] != -1) continue; //이미 방문헀으면 pass
check[y] = check[x]+1; // 노드마다 값 누적
cnt += check[y]; // 누적값을 합산
qu.add(y);
}
}
return cnt;
}
}
'Knowledge > 알고리즘' 카테고리의 다른 글
백준 1697 번: 숨바꼭질 (java) (0) | 2024.02.21 |
---|---|
백준 5430번: AC(java) (0) | 2024.01.17 |
백준 1012 번 : 유기농 배추 (java) (0) | 2023.12.19 |
백준 2615 번: 오목 (java) (0) | 2023.12.14 |
백준 1914번: 하노이 탑(java) (0) | 2023.12.12 |