Skip to content

Commit 0016a9a

Browse files
committed
전력망을 둘로 나누기 / 심화
1 parent ddfb81f commit 0016a9a

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
function solution(n, wires) {
2+
const graph = Array.from({ length: n + 1 }, () => []);
3+
4+
for (const [v1, v2] of wires) {
5+
graph[v1].push(v2);
6+
graph[v2].push(v1);
7+
}
8+
9+
let minDifference = Number.MAX_VALUE;
10+
11+
const dfs = (node, visited) => {
12+
let count = 1;
13+
visited[node] = true;
14+
15+
for (const neighbor of graph[node]) {
16+
if (!visited[neighbor]) {
17+
count += dfs(neighbor, visited);
18+
}
19+
}
20+
21+
return count;
22+
};
23+
24+
for (const [v1, v2] of wires) {
25+
const visited = Array(n + 1).fill(false);
26+
visited[v1] = true;
27+
const count = dfs(v2, visited);
28+
const difference = Math.abs(count - (n - count));
29+
minDifference = Math.min(minDifference, difference);
30+
}
31+
32+
return minDifference;
33+
}

0 commit comments

Comments
 (0)