File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 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+ ```
You can’t perform that action at this time.
0 commit comments