1- import java .util .ArrayList ;
2- import java .util .LinkedList ;
3- import java .util .Queue ;
1+ import java .util .*;
42class Solution {
5- ArrayList <Integer >[] neighbours ;
3+ boolean [] visited ;
4+ int answer ;
65 public int solution (int n , int [][] wires ) {
7- neighbours = new ArrayList [n +1 ];
8-
9- for (int i = 1 ; i <= n ; i ++) {
10- neighbours [i ] = new ArrayList <>();
11- }
12-
13- for (int [] wire : wires ) {
14- int tower1 = wire [0 ];
15- int tower2 = wire [1 ];
16-
17- // 서로에게 연결된 송전탑 기록
18- neighbours [tower1 ].add (tower2 );
19- neighbours [tower2 ].add (tower1 );
20- }
21-
22- int count = n ;
23- int diff = 0 ;
24- int min = Integer .MAX_VALUE ;
25- for (int [] wire : wires ) {
26- int tower1 = wire [0 ];
27- int tower2 = wire [1 ];
28-
29- // 송전탑 사이를 끊으면 각자 갖는 연결된 송전탑 갯수
30- count = bfs (tower1 , tower2 , n );
31- diff = Math .abs (count - (n - count ));
32- min = Math .min (diff , min );
6+ answer = n ;
7+ visited = new boolean [n +1 ];
8+
9+ for (int [] wire : wires ){
10+ int towerA = wire [0 ];
11+ int towerB = wire [1 ];
12+ visited [towerB ] = true ;
13+ visited [towerA ] = true ;
14+ int cnt = dfs (towerA ,wires ,n ); // towerA와 연결된 타워만 찾으면 됨
15+ visited [towerA ] = false ;
16+ visited [towerB ] = false ;
17+
18+ answer = Math .min (Math .abs (n - (2 * cnt )), answer );
3319 }
34- return min ;
20+
21+ return answer ;
3522 }
36-
37- private int bfs (int tower1 , int tower2 , int n ) {
38- boolean [] visited = new boolean [n + 1 ];
39- Queue <Integer > queue = new LinkedList <>();
40-
41- queue .add (tower1 );
42- visited [tower1 ] = true ;
43- int count = 1 ;
44-
45- while (!queue .isEmpty ()) {
46- int current = queue .poll (); // 현재 탐색중인 타워
47-
48- for (int neighbour : neighbours [current ]){
49- if (!visited [neighbour ] && neighbour != tower2 ){
50- visited [neighbour ] = true ; // 방문 처리
51- queue .add (neighbour ); // 다음에 탐색할 송전탑
52- count ++; // 송전탑 개수
53- }
23+
24+ int dfs (int towerA , int [][] wires , int n ){
25+ int cnt = 1 ;
26+ for (int [] wire : wires ){
27+
28+ // 연결된 송전탑 찾음(방문한적 x)
29+ if (wire [0 ] == towerA && !visited [wire [1 ]]) {
30+ visited [wire [1 ]] = true ; // 방문 처리
31+ cnt += dfs (wire [1 ],wires ,n ); // dfs
32+ visited [wire [1 ]] = false ; // 백트래킹
33+
34+ } else if (wire [1 ] == towerA && !visited [wire [0 ]]) {
35+ visited [wire [0 ]] = true ; // 방문 처리
36+ cnt += dfs (wire [0 ],wires , n ); // dfs
37+ visited [wire [0 ]] = false ; // 백트래킹
5438 }
5539 }
56-
57- return count ;
40+
41+ return cnt ;
5842 }
43+
5944}
0 commit comments