https://www.acmicpc.net/problem/6118
6118번: 숨바꼭질
재서기는 수혀니와 교외 농장에서 숨바꼭질을 하고 있다. 농장에는 헛간이 많이 널려있고 재서기는 그 중에 하나에 숨어야 한다. 헛간의 개수는 N(2 <= N <= 20,000)개이며, 1 부터 샌다고 하자. 재
www.acmicpc.net
저는 해당 문제를 BFS를 이용하여 문제를 해결하였습니다.
BFS를 통해 1번에서 출발하여 가장 먼 곳이 어디인지를 찾았고 이때의 거리(time)와 가장 작은 숫자(resultNum)와 개수(cnt)를 구하였습니다.
package BOJ.BFS;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.StringTokenizer;
import java.util.function.Function;
public class BOJ_6118 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine()," ");
Function<String,Integer> stoi = Integer::parseInt;
int n = stoi.apply(st.nextToken());
int m = stoi.apply(st.nextToken());
List<Integer>[] map = new List[n+1];
for(int i = 0 ; i <= n ; i++){
map[i] = new ArrayList<>();
}
for(int i = 0 ; i < m ; i++){
st = new StringTokenizer(br.readLine()," ");
int a = stoi.apply(st.nextToken());
int b = stoi.apply(st.nextToken());
map[a].add(b);
map[b].add(a);
}
int[] result = bfs(map,n);
for(int num : result){
System.out.print(num+" ");
}
}
private static int INF = 987654321;
private static int[] bfs(List<Integer>[] map, int n) {
Queue<Integer> q = new LinkedList<>();
q.offer(1);
boolean[] visited = new boolean[n+1];
visited[1] = true;
int time = -1;
int cnt = 0;
int resultNum = INF;
while(!q.isEmpty()){
int size = q.size();
resultNum = INF;
cnt = size;
for(int s = 0 ; s < size ; s++){
int now = q.poll();
resultNum = Math.min(now,resultNum);
for(int next : map[now]){
if(!visited[next]){
visited[next] = true;
q.offer(next);
}
}
}
time++;
}
return new int[] {resultNum,time,cnt};
}
}
'알고리즘' 카테고리의 다른 글
백준 1026번 보물 (JAVA) (0) | 2022.05.03 |
---|---|
백준 16437번 양 구출 작전 (JAVA) (0) | 2022.05.02 |
백준 2617번 구슬 찾기 (JAVA) (0) | 2022.04.30 |
백준 15971번 두 로봇 (JAVA) (0) | 2022.04.29 |
백준 2406번 안정적인 네트워크 (JAVA) (0) | 2022.04.28 |