Skip to content

Commit 145b380

Browse files
committed
Feat: 그래프 가장 먼 노드(레벨3)
1 parent 8588d76 commit 145b380

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
function solution(n, edge) {
2+
const graph = Array.from(Array(n + 1), () => []);
3+
let distance = Array(n + 1).fill(0);
4+
5+
edge.forEach(([u, v]) => {
6+
graph[u].push(v);
7+
graph[v].push(u);
8+
});
9+
10+
bfs(1);
11+
12+
function bfs(i) {
13+
const queue = [i];
14+
distance[i] = 1;
15+
16+
while (queue.length) {
17+
const x = queue.shift();
18+
19+
graph[x].forEach((e) => {
20+
if (distance[e] === 0) {
21+
distance[e] = distance[x] + 1;
22+
queue.push(e);
23+
}
24+
});
25+
}
26+
}
27+
const max = Math.max(...distance);
28+
29+
return distance.filter((e) => e === max).length;
30+
}

0 commit comments

Comments
 (0)