https://programmers.co.kr/learn/courses/30/lessons/49189
function solution(n, edges) {
const graph = new Array(n+1).fill().map(_ => []);
for(const edge of edges) {
graph[edge[0]].push(edge[1]);
graph[edge[1]].push(edge[0]);
}
console.log(graph)
const queue = [1];
const visited = [null, 1];
while(queue.length){
const node = queue.shift();
//console.log(node)
for(const item of graph[node]){
if(!visited[item]){
visited[item]=visited[node]+1;
queue.push(item)
}
}
}
const max = visited.sort((a,b)=>b-a)[0];
return visited.filter(item=>item===max).length
}
우선, 그래프는 다음과 같이 만들었다
이 상황에서 일반적인 BFS 방식을 사용하면서 순차적을 노드들을 탐색해 나갔는데,
기존에 달라진 부분은 visited 부분이다.
const visited = [null, 1];
기존과 다르게 visited가 false로 이루어진 배열로 초기화되지 않은 것을 확인할 수 있다.
이렇게 한 이유는 다음과 같다.
false가 아니더라도 if(!visited[item])
는 visited[item]의 값이 없어도 true를 반환하기 때문
BFS에서 깊이를 구분하기 위해서
따라서 최종 결과, visited는 [null, 1, 2, 3, 3, 3]
이 나온다.
여기서 max 값을 구한 후, max와 일치하는 visited의 요소의 개수를 return 시켜주면 된다.