function solution(n, edge) {
// Graph 생성
const graph = Array.from(new Array(n + 1), () => []);
// Graph 추가
for (let i = 0; i < edge.length; i++) {
const [start, end] = edge[i];
graph[start].push(end);
graph[end].push(start);
}
// distance 만들기
const distance = Array(n + 1).fill(0);
distance[1] = 1;
// BFS
const queue = [1];
while (queue.length > 0) {
const element = queue.shift();
for (let item of graph[element]) {
if (distance[item] === 0) {
queue.push(item);
distance[item] += distance[element] + 1;
}
}
}
const maxNum = Math.max(...distance);
return distance.filter((item) => item === maxNum).length;
}
=> 2차원 배열을 통해 그래프를 생성한다. 생성 한 뒤, 첫 요소를 큐에 넣고 BFS를 수행한다. BFS를 수행할 때에는 거리가 0일 때만 삽입하고 거리에는 이전에 왔던 거리 + 1을 넣어준다.