|
3 | 3 | class Solution { |
4 | 4 | boolean[] visited; |
5 | 5 | public int solution(int n, int[][] wires) { |
| 6 | + |
6 | 7 | visited = new boolean[n+1]; |
7 | | - int answer = n; |
8 | | - int cnt = 1; |
| 8 | + int min = n; |
| 9 | + |
9 | 10 | for(int[] wire : wires) { |
10 | 11 | int towerA = wire[0]; |
11 | 12 | int towerB = wire[1]; |
12 | | - |
13 | | - // towerA와 연결된 타워의 갯수 |
| 13 | + int cnt = 0; |
| 14 | + |
14 | 15 | visited[towerA] = true; |
15 | 16 | visited[towerB] = true; |
16 | | - cnt = dfs(towerA,wires); |
| 17 | + |
| 18 | + cnt += dfs(towerA,wires); |
| 19 | + |
17 | 20 | visited[towerA] = false; |
18 | 21 | visited[towerB] = false; |
19 | 22 |
|
20 | | - answer = Math.min(Math.abs((n - cnt) - cnt),answer); |
| 23 | + min = Math.min(min, Math.abs(n - cnt - cnt)); |
21 | 24 | } |
22 | | - return answer; |
| 25 | + |
| 26 | + return min; |
23 | 27 | } |
24 | 28 |
|
25 | | - public int dfs(int towerA, int[][] wires){ |
26 | | - int cnt = 1; |
| 29 | + int dfs(int target, int[][] wires){ |
27 | 30 |
|
28 | | - for(int i = 0; i < wires.length; i++) { |
29 | | - int[] wire = wires[i]; |
| 31 | + int cnt = 1; |
| 32 | + for(int[] wire : wires) { |
| 33 | + int towerA = wire[0]; |
| 34 | + int towerB = wire[1]; |
30 | 35 |
|
31 | | - if(towerA == wire[0] && !visited[wire[1]]){ |
32 | | - visited[wire[1]] = true; |
33 | | - cnt += dfs(wire[1], wires); |
34 | | - visited[wire[1]] = false; |
35 | | - } else if(towerA == wire[1] && !visited[wire[0]]){ |
36 | | - visited[wire[0]] = true; |
37 | | - cnt += dfs(wire[0], wires); |
38 | | - visited[wire[0]] = false; |
| 36 | + if(target == towerA && !visited[towerB]) { |
| 37 | + visited[towerB] = true; |
| 38 | + cnt += dfs(towerB,wires); |
| 39 | + visited[towerB] = false; |
| 40 | + } else if(target == towerB && !visited[towerA]){ |
| 41 | + visited[towerA] = true; |
| 42 | + cnt += dfs(towerA,wires); |
| 43 | + visited[towerA] = false; |
39 | 44 | } |
40 | 45 | } |
41 | 46 |
|
|
0 commit comments