새소식

Programmers

[Programmers] 가장 먼 노드 문제 - (javascript)

  • -
728x90
문제 이름 :  가장 먼 노드

 

<<< 문제 내용 >>>

 

function solution(n, vertex) { let answer = []; const graph = Array.from(Array(n + 1), () => new Array()); for (const el of vertex) { graph[el[0]].push(el[1]); graph[el[1]].push(el[0]); } const bfs = (start, count) => { let queue = [[start, count]]; let visited = new Array(n + 1).fill(false); visited[1] = true; while (queue.length) { let [next, count] = queue.shift(); for (const t of graph[next]) { if (!visited[t]) { queue.push([t, count + 1]); visited[t] = true; } } answer.push(count); } }; bfs(1, 0); return answer.reduce((a, c) => (c === Math.max(...answer) ? a + 1 : a)); }

* 정점과 간선을 이용한 문제로 가장 먼 노드의 수만 BFS를 이용하여 구하면 되는 문제입니다.

간선에 대한 가중치가 없고, 특별한 조건이 없는 문제여서 쉬운 문제였습니다.

 

 

도움이 되셨다면 공감 부탁드립니다.

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.