Skip to content

Commit c84e7de

Browse files
committed
Feat: 가장 먼 노드 (레벨 3)
1 parent cf258c3 commit c84e7de

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
function solution(n, edge) {
2+
const que = [[1, 0]];
3+
const graph = {};
4+
edge.forEach((v) => {
5+
if (!graph[v[0]]) graph[v[0]] = [v[1]];
6+
else graph[v[0]].push(v[1]);
7+
8+
if (!graph[v[1]]) graph[v[1]] = [v[0]];
9+
else graph[v[1]].push(v[0]);
10+
});
11+
const visited = Array.from({ length: n + 1 }, () => false);
12+
const cnts = Array.from({ length: n + 1 }, () => 0);
13+
let index = 0;
14+
visited[1] = true;
15+
while (que.length > 0) {
16+
const [node, cnt] = que.shift();
17+
index = cnt;
18+
cnts[cnt] += 1;
19+
20+
for (const next of graph[node]) {
21+
if (visited[next]) continue;
22+
que.push([next, cnt + 1]);
23+
visited[next] = true;
24+
}
25+
}
26+
return cnts[index];
27+
}

0 commit comments

Comments
 (0)