
#풀이
import java.io.*;
import java.util.*;
public class Main {
static int N, M;
static ArrayList<Integer>[] graph;
static int[] dist;
static boolean[] visited;
public static void bfs(int start) {
Queue<Integer> queue = new LinkedList<>();
queue.add(start);
visited[start] = true;
dist[start] = 0;
while (!queue.isEmpty()) {
int now = queue.poll();
for (int next : graph[now]) {
if (!visited[next]) {
visited[next] = true;
dist[next] = dist[now] + 1;
queue.add(next);
}
}
}
}
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());
M = Integer.parseInt(st.nextToken());
graph = new ArrayList[N + 1];
visited = new boolean[N + 1];
dist = new int[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 a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
graph[a].add(b);
graph[b].add(a);
}
bfs(1);
int maxDist = 0;
int ans = 0;
int count = 0;
for (int i = 1; i <= N; i++) {
if (dist[i] > maxDist) {
maxDist = dist[i];
ans = i;
count = 1;
} else if (dist[i] == maxDist) {
count++;
}
}
System.out.println(ans + " " + maxDist + " " + count);
}
}
#성능

#정리
bfs탐색을 통해 1번 노드부터 모든 노드까지의 최단거리를 구한다.
이후 가장 멀리 떨어진 노드와 해당 거리와 같은 거리에 있는 노드들을 찾는다.
'PS' 카테고리의 다른 글
[백준] 1149번 : RGB거리[Java] (0) | 2025.07.22 |
---|---|
[백준] 5214번 : 환승[Java] (0) | 2025.07.22 |
[백준] 11054번 : 가장 긴 바이토닉 부분 수열[Java] (0) | 2025.07.19 |
[백준] 1806번 : 부분합[Java] (2) | 2025.07.18 |
[백준] 5639번 : 이진 검색 트리[Java] (1) | 2025.07.17 |