[PS] 99ํด๋ฝ ์ฝํ ์คํฐ๋ 36์ผ์ฐจ TIL (์ ๋ ฅ๋ง์ ๋๋ก ๋๋๊ธฐ)
ํ๊ทธ: 99ํด๋ฝ, BFS/DFS, PS, TIL, ์์ ํ์, ์ฝ๋ฉํ ์คํธ์ค๋น, ํญํด99
์นดํ ๊ณ ๋ฆฌ: PS
![]()
๋ฌธ์


์ค๋ช
์ต์ด ๊ทธ๋ํ ๊ฐ์ ์ ๋ณด๊ฐ ์ฃผ์ด์ง๊ณ , ํด๋น ๊ทธ๋ํ์์ ๊ฐ์ ์ ํ๋์ฉ ๋์์ ๋ ๋ ๋ถ๋ถ์ผ๋ก ๋๋์ด์ง๋ ๊ทธ๋ํ์ ๋ ธ๋ ์ ์ฐจ์ด๊ฐ ์ต์๊ฐ ๋๋๋ก ํ๋ ๋ฌธ์
ํ์ด
์ ์์๋ฅผ ์ธ์ ํ๋ ฌ ๊ทธ๋ํ๋ก ๋ํ๋ด๋ฉด ์๋์ ๊ฐ๋ค.

-
graph ์ ์ธ : ์ ์ ๊ณผ ๊ฐ์ ์ ๋ณด๊ฐ ์ฃผ์ด์ง๋ฏ๋ก ํด๋น ์ขํ๋ฅผ ์๋ฐฉํฅ ์ฐ๊ฒฐํ๊ธฐ ์ํด
int[][]๋ก graph ๋ฅผ ์ ์ธํด์คฌ๋ค.boolean[][]๋ก ์ ์ธํด๋ ์๊ด์๋ค. - graph ์ธํ
: ์๋ฐฉํฅ ์ฐ๊ฒฐ์ ์ํด ๋ค์๊ณผ ๊ฐ์ด ๊ทธ๋ํ ์ด๊ธฐ ์ธํ
์ ์งํํ๋ค.
1 2
graph[wire[0]][wire[1]] = 1; graph[wire[1]][wire[0]] = 1;
- ๊ฐ์ ๋๊ธฐ : ๋ค์๊ณผ ๊ฐ์ด ๊ฐ์ ์ ํ๋์ฉ ๋์์ ๋์ ๋
ธ๋ ์๋ฅผ ์ผ๋ค.
1 2 3 4 5
// ๊ฐ์ ์ ๋๊ณ graph[u][v] = 0; graph[v][u] = 0; // ๊ทธ ๊ทธ๋ํ๋ฅผ dfs ๋๋ฆฐ๋ค. ๋ฌธ์ ์์ n ์ ์์ฐ์๋ผ๊ณ ํ์ผ๋ฏ๋ก graph ๋ 1๋ถํฐ ์ธํ ๋์ด ์๋ค. dfs(1, visited, graph);
- ๋
ธ๋ ์ ์ฐจ์ด๊ฐ ์ต์๊ฐ ๋๋ ๊ฐ ์ฐพ๊ธฐ : dfs ์์ ์ฐพ์ ํ ๊ทธ๋ํ์ ๋
ธ๋ ์๊ฐ
count๋ผ๋ฉด, ๋๋จธ์ง ๊ทธ๋ํ์ ๋ ธ๋ ์๋n - count๊ฐ ๋๋ค. ์ด ๋ ์์ ์ฐจ์ด๋ฅผ ๊ตฌํ๊ณ ๊ธฐ์กด์ ์ต์๊ฐ ๋ณด๋ค ์์ ๊ฒฝ์ฐminDiff๋ฅผ ๊ฐฑ์ ํด ๋๊ฐ๋ค. - ๊ฐ์ ๋ณต๊ตฌ : ๋์๋ ๊ฐ์ ์ ๋ค์ ์ฐ๊ฒฐ์์ผ ์ฃผ๊ณ , ๋ค์ wire ์ ๋ํด ํ์ํ๋ค.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
static int[][] graph;
static boolean[] visited;
public int solution(int n, int[][] wires) {
graph = new int[n + 1][n + 1];
for (int[] wire : wires) {
graph[wire[0]][wire[1]] = 1;
graph[wire[1]][wire[0]] = 1;
}
int minDiff = Integer.MAX_VALUE;
for (int[] wire : wires) {
int u = wire[0];
int v = wire[1];
graph[u][v] = 0;
graph[v][u] = 0;
visited = new boolean[n + 1];
int count1 = dfs(1, visited, graph);
int count2 = n - count1;
int diff = Math.abs(count1 - count2);
minDiff = Math.min(minDiff, diff);
graph[u][v] = 1;
graph[v][u] = 1;
}
return minDiff;
}
private int dfs(int node, boolean[] visited, int[][] graph) {
visited[node] = true;
int count = 1;
for (int i = 1; i < graph.length; i++) {
if (!visited[i] && graph[node][i] == 1) {
count += dfs(i, visited, graph);
}
}
return count;
}
}
๋๊ธ๋จ๊ธฐ๊ธฐ