코딩테스트
[못풀었다/프로그래머스] 가장 먼 노드
_서리__
2023. 6. 10. 13:54
function solution(n, edge) {
var answer = 0;
const graph = Array.from({length:n+1},()=>[])
for(let i=0;i<edge.length;i++){
graph[edge[i][0]].push(edge[i][1])
graph[edge[i][1]].push(edge[i][0])
}
const visited = Array.from({length:n+1},()=>false)
const distance = Array.from({length:n+1},()=>0)
bfs(graph,visited,distance)
let max = Math.max(...distance)
return distance.filter((el)=>el===max).length
return answer;
}
function bfs(graph,visited,distance){
const queue = [1];
visited[1] = true;
while(queue.length){
let node = queue.shift();
graph[node].forEach((nodes)=>{
if(!visited[nodes]){
queue.push(nodes)
visited[nodes] = true;
distance[nodes] = distance[node]+1;
}
})
}
}
bfs로 풀어야겠다는 생각까지는 했는데 distance를 어떻게 처리해야할지 막막했다.
현재 노드의 distance에 +1을 하면 다음 노드의 distance가 된다!