Skip to content

Commit 35e70b9

Browse files
authored
[20251031] PGM / Lv2 / 전력망을 둘로 나누기 / 이강현
1 parent d5e17a3 commit 35e70b9

File tree

1 file changed

+42
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)