Skip to content

Commit bee6d5b

Browse files
authored
[20250926] PGM / LV2 / 전력망을 둘로 나누기 / 김수연
[20250926] PGM / LV2 / 전력망을 둘로 나누기 / 김수연
2 parents 925d4df + b1412f9 commit bee6d5b

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
```java
2+
import java.util.*;
3+
class Solution {
4+
static int N;
5+
static List<List<Integer>> graph;
6+
public int solution(int n, int[][] wires) {
7+
int answer = Integer.MAX_VALUE;
8+
N = n;
9+
graph = new ArrayList<>();
10+
for (int i = 0; i <= n; i++) graph.add(new ArrayList<>());
11+
for (int i = 0; i < n-1; i++) {
12+
graph.get(wires[i][0]).add(wires[i][1]);
13+
graph.get(wires[i][1]).add(wires[i][0]);
14+
}
15+
for (int i = 0; i < n-1; i++) {
16+
answer = Math.min(answer, check(wires[i][0], wires[i][1]));
17+
}
18+
19+
return answer;
20+
}
21+
22+
private int check(int a, int b) {
23+
Queue<Integer> q = new LinkedList<>();
24+
boolean[] visited = new boolean[N+1];
25+
int cnt = 1;
26+
visited[1] = true;
27+
q.add(1);
28+
while(!q.isEmpty()) {
29+
int curr = q.poll();
30+
for (int next : graph.get(curr)) {
31+
if (visited[next] || (a==curr && b==next) || (a==next && b==curr)) continue;
32+
cnt++;
33+
visited[next] = true;
34+
q.add(next);
35+
}
36+
}
37+
return Math.abs((N-cnt) - cnt);
38+
}
39+
}
40+
```

0 commit comments

Comments
 (0)