Skip to content

Commit 4a84840

Browse files
committed
전력망을_둘로_나누기 /심화
1 parent 5abc1e3 commit 4a84840

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
function solution(n, wires) {
2+
let answer = Infinity;
3+
4+
function dfs(graph, start, visited) {
5+
visited[start] = true;
6+
let count = 1;
7+
8+
for (let i = 0; i < graph[start].length; i++) {
9+
const neighbor = graph[start][i];
10+
if (!visited[neighbor]) {
11+
count += dfs(graph, neighbor, visited);
12+
}
13+
}
14+
15+
return count;
16+
}
17+
18+
for (let i = 0; i < n - 1; i++) {
19+
const graph = Array(n)
20+
.fill(null)
21+
.map(() => []);
22+
for (let j = 0; j < n - 1; j++) {
23+
if (i === j) continue;
24+
const [a, b] = wires[j];
25+
graph[a - 1].push(b - 1);
26+
graph[b - 1].push(a - 1);
27+
}
28+
29+
const visited = Array(n).fill(false);
30+
let count1 = 0;
31+
let count2 = 0;
32+
33+
for (let j = 0; j < n; j++) {
34+
if (!visited[j]) {
35+
if (count1 === 0) {
36+
count1 = dfs(graph, j, visited);
37+
} else {
38+
count2 = dfs(graph, j, visited);
39+
}
40+
}
41+
}
42+
43+
const diff = Math.abs(count1 - count2);
44+
answer = Math.min(answer, diff);
45+
}
46+
47+
return answer;
48+
}

0 commit comments

Comments
 (0)