1+ import java .util .List ;
12import java .util .ArrayList ;
2- import java .util .Arrays ;
33
44class Solution {
5- static boolean [] visited ;
6- static ArrayList <Integer >[] adjList ;
7- static int count = 0 ;
8-
5+
6+ static List <Integer >[] wiresInfo ;
7+ static int answer ;
8+
99 public int solution (int n , int [][] wires ) {
10- int answer = Integer .MAX_VALUE ;
11- adjList = new ArrayList [n + 1 ];
12- visited = new boolean [n + 1 ];
13-
10+ wiresInfo = new ArrayList [n + 1 ];
11+ answer = Integer .MAX_VALUE ;
12+
1413 for (int i = 1 ; i <= n ; i ++) {
15- adjList [i ] = new ArrayList <>();
14+ wiresInfo [i ] = new ArrayList <>();
1615 }
17-
16+
1817 for (int i = 0 ; i < wires .length ; i ++) {
19- adjList [wires [i ][0 ]].add (wires [i ][1 ]);
20- adjList [wires [i ][1 ]].add (wires [i ][0 ]);
18+ wiresInfo [wires [i ][0 ]].add (wires [i ][1 ]);
19+ wiresInfo [wires [i ][1 ]].add (wires [i ][0 ]);
2120 }
2221
2322 for (int [] wire : wires ) {
24- adjList [wire [0 ]].remove (Integer .valueOf (wire [1 ]));
25- adjList [wire [1 ]].remove (Integer .valueOf (wire [0 ]));
26-
27- dfs (1 );
28- answer = Math .min (answer , Math .abs (count - (n - count )));
23+ int wireCut1 = wire [0 ];
24+ int wireCut2 = wire [1 ];
25+ boolean [] visited = new boolean [n + 1 ];
2926
30- count = 0 ;
31- Arrays .fill (visited , false );
32- adjList [wire [0 ]].add (wire [1 ]);
33- adjList [wire [1 ]].add (wire [0 ]);
27+ int count = dfs (1 , visited , wireCut1 , wireCut2 );
28+ answer = Math .min (answer , Math .abs (count - (n - count )));
3429 }
35-
30+
3631 return answer ;
3732 }
38-
39- private void dfs (int node ) {
40- visited [node ] = true ;
41- count ++;
42- for (int nextNode : adjList [node ]) {
43- if (!visited [nextNode ]) {
44- dfs (nextNode );
33+
34+ private int dfs (int start , boolean [] visited , int wireCut1 , int wireCut2 ) {
35+ visited [start ] = true ;
36+ int count = 1 ;
37+
38+ for (int nextWire : wiresInfo [start ]) {
39+ if (start == wireCut1 && nextWire == wireCut2 || nextWire == wireCut1 && start == wireCut2 ) {
40+ continue ;
41+ }
42+
43+ if (!visited [nextWire ]) {
44+ count += dfs (nextWire , visited , wireCut1 , wireCut2 );
4545 }
4646 }
47+
48+ return count ;
4749 }
48- }
50+ }
0 commit comments