Skip to content

Commit 254dfac

Browse files
committed
[level 2] Title: 전력망을 둘로 나누기, Time: 2.15 ms, Memory: 83.2 MB -BaekjoonHub
1 parent 2776a33 commit 254dfac

File tree

2 files changed

+35
-33
lines changed

2 files changed

+35
-33
lines changed

프로그래머스/2/86971. 전력망을 둘로 나누기/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
### 성능 요약
66

7-
메모리: 83.5 MB, 시간: 2.39 ms
7+
메모리: 83.2 MB, 시간: 2.15 ms
88

99
### 구분
1010

@@ -16,7 +16,7 @@
1616

1717
### 제출 일자
1818

19-
2026년 01월 26일 18:15:20
19+
2026년 02월 16일 16:58:44
2020

2121
### 문제 설명
2222

Lines changed: 33 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,50 @@
1+
import java.util.List;
12
import java.util.ArrayList;
2-
import java.util.Arrays;
33

44
class 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

Comments
 (0)