
import java.util.*;
class Solution {
    static ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
    static int answer=0;
    static boolean[] ch;
    static int[] dis;
    static int max = Integer.MIN_VALUE;
    
    public static void BFS(int v){
        ch[v]=true;
        dis[v]=0;
        
        Queue<Integer> Q = new LinkedList<>();
        Q.offer(v);
        while(!Q.isEmpty()){
            int x = Q.poll();
            for(int nx : graph.get(x)){
                if(!ch[nx]){
                    ch[nx]=true;
                    Q.offer(nx);
                    dis[nx]=dis[x]+1;
                    if(dis[nx]>max) max=dis[nx];
                }
            }
        }
    }
    
    
    public int solution(int n, int[][] edge) {
        
        for(int i=0; i<=n; i++) graph.add(new ArrayList<>());
        
        for(int[] x : edge){
            int v = x[0];
            int w = x[1];
            graph.get(v).add(w);
            graph.get(w).add(v);
        }
        
        ch = new boolean[n+1];
        dis = new int[n+1];
        BFS(1);
        
        for(int num : dis){
            if(num == max) answer++;
        }
        return answer;
    }
}
일단 이런 그래프 문제에서 거리를 구하는 핵심.
위 조건을 지키면서 Q로 while()문을 오지게 돌려주면 쉽게 푼다.