• 문제 링크
6118번: 숨바꼭질
재서기는 수혀니와 교외 농장에서 숨바꼭질을 하고 있다. 농장에는 헛간이 많이 널려있고 재서기는 그 중에 하나에 숨어야 한다. 헛간의 개수는 N(2 <= N <= 20,000)개이며, 1 부터 샌다고 하자. 재
www.acmicpc.net
• 풀이 과정
• 풀이 코드
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int n, m, num, maxDist, cnt;
static List<Integer>[] graph;
static boolean[] visit;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
graph = new ArrayList[n + 1];
for (int i = 0; i <= n; i++)
graph[i] = new ArrayList<>();
for (int i = 0; i < m; i++) {
st = new StringTokenizer(br.readLine());
int src = Integer.parseInt(st.nextToken());
int dest = Integer.parseInt(st.nextToken());
graph[src].add(dest);
graph[dest].add(src);
}
bfs();
bw.write(num + " " + maxDist + " " + cnt);
bw.flush();
}
private static void bfs() {
Queue<Edge> q = new LinkedList<>();
q.offer(new Edge(1, 0));
visit = new boolean[n + 1];
visit[1] = true;
while (!q.isEmpty()) {
Edge edge = q.poll();
int src = edge.node;
int dist = edge.weight;
if (maxDist < dist) {
maxDist = dist;
num = src;
cnt = 1;
} else if (maxDist == dist) {
if (num > src)
num = src;
cnt++;
}
for (int dest : graph[src]) {
if (visit[dest])
continue;
q.offer(new Edge(dest, dist + 1));
visit[dest] = true;
}
}
}
private static class Edge {
int node, weight;
public Edge(int node, int weight) {
this.node = node;
this.weight = weight;
}
}
}
'Problem Solving > Baekjoon' 카테고리의 다른 글
[백준] 20301 반전 요세푸스 - Data Structure / Java (0) | 2022.12.11 |
---|---|
[백준] 3184 양 - Graph Theory / Java (0) | 2022.12.10 |
[백준] 2660 회장뽑기 - Graph Theory / Java (0) | 2022.12.08 |
[백준] 5567 결혼식 - Graph Theory / Java (0) | 2022.12.07 |
[백준] 17626 Four Squares - Dynamic Programming / Java (1) | 2022.12.06 |
댓글