Skip to content

Commit 61e773b

Browse files
committed
feat: 가장 먼 노드
1 parent 0563074 commit 61e773b

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
function solution (n, edge) {
2+
//1. 연결리스트 생성
3+
const connects = new Array(n).fill().map(_ => []);
4+
5+
//2. 양방향으로 연결리스트를 채워줌
6+
//edge 배열의 각 요소에 대해 반복
7+
for(const e of edge) {
8+
connects[e[0]-1].push(e[1]-1);
9+
connects[e[1]-1].push(e[0]-1);
10+
}
11+
12+
const visited = [1];
13+
const queue = [0];
14+
while(queue.length) {
15+
const cur = queue.shift();
16+
17+
for(const next of connects[cur]) {
18+
if(!visited[next]) {
19+
visited[next] = visited[cur] + 1;
20+
queue.push(next);
21+
}
22+
}
23+
}
24+
//visited 배열에서 최대 거리를 구한다
25+
const max = Math.max(...visited);
26+
//최대 거리와 같은 값을 가지는 요소들의 개수를 세어 반환
27+
return visited.filter(el => el === max).length;
28+
}

0 commit comments

Comments
 (0)