https://school.programmers.co.kr/learn/courses/30/lessons/86971
ํ๋ก๊ทธ๋๋จธ์ค
์ฝ๋ ์ค์ฌ์ ๊ฐ๋ฐ์ ์ฑ์ฉ. ์คํ ๊ธฐ๋ฐ์ ํฌ์ง์ ๋งค์นญ. ํ๋ก๊ทธ๋๋จธ์ค์ ๊ฐ๋ฐ์ ๋ง์ถคํ ํ๋กํ์ ๋ฑ๋กํ๊ณ , ๋์ ๊ธฐ์ ๊ถํฉ์ด ์ ๋ง๋ ๊ธฐ์ ๋ค์ ๋งค์นญ ๋ฐ์ผ์ธ์.
programmers.co.kr
1. ๋ฌธ์
ํธ๋ฆฌํํ๋ก N๊ฐ์ ์ก์ ํ์ด ์ฃผ์ด์ง๋ค. ์ด ์ฐ๊ฒฐ๋ ์ ์ ๋ค ์ค ํ๋๋ฅผ ๋์ด์ ๋คํธ์ํฌ๋ฅผ 2๊ฐ๋ก ๋ถํ ํ๋ ค๊ณ ํ๋ค.
๋ถํ ๋ ๋ ๋คํธ์ํฌ๊ฐ ๊ฐ๋ ์ก์ ํ์ ๊ฐ์์ ์ฐจ์ ์ ๋๊ฐ์ด ์ต์๊ฐ๋ ๋์ ์ ๋๊ฐ์ ๋ฆฌํดํ๋ค.
2. ํ์ด
bfs๋ก ํ์๋ค.
์ด ๋ฌธ์ ๋ ์ ํ์ฌํญ์ ์ ์ฝ์ด์ผ ํ๋ค. wires๋ ๊ธธ์ด๊ฐ n-1์ธ ์ ์ํ 2์ฐจ์ ๋ฐฐ์ด์ด๋ค.
์๋์ ๊ฐ์ ๋ก์ง์ผ๋ก ํ์๋ค.
0. min์ Integer.MAX_VALUE๋ก ์ต๋๊ฐ์ผ๋ก ์ด๊ธฐํํ๋ค.
for๋ฌธ์ ๋๋ ค
1. ์ฐ๊ฒฐ์ ํ๋์ฉ ๋์ ํ
2. 2๊ฐ์ ๋คํธ์ํฌ์์ ๊ฐ๊ฐ bfs๋ฅผ ๋๋ ค ๋ ธ๋ ๊ฐ์๋ฅผ ๊ตฌํ๋ค.
3. ๋ ๊ฐ์์ ์ฐจ์ ์ ๋๊ฐ๊ณผ min์ ๋น๊ตํด min์ ๊ฐฑ์ ํ๋ค.
4. ๋์๋ ์ฐ๊ฒฐ์ ๋ค์ ์ฐ๊ฒฐ์ํจ๋ค.
3. ์ฝ๋
import java.io.*;
import java.util.*;
class Solution {
static int min, N, matrix[][];
public int solution(int n, int[][] wires) {
N = n;
matrix = new int[N+1][N+1];
for (int i=0; i<N-1; i++) {
matrix[wires[i][0]][wires[i][1]] = 1;
matrix[wires[i][1]][wires[i][0]] = 1;
}
min = Integer.MAX_VALUE;
for (int i=0; i<N-1; i++) {
int s1 = wires[i][0];
int s2 = wires[i][1];
// ์ฐ๊ฒฐ ๋์
matrix[s1][s2] = 0;
matrix[s2][s1] = 0;
int cnt1 = bfs(s1);
int cnt2 = bfs(s2);
min = Math.min(min, Math.abs(cnt1-cnt2));
// ๋ค์ ์ฐ๊ฒฐ
matrix[s1][s2] = 1;
matrix[s2][s1] = 1;
}
return min;
}
static int bfs(int num){
Queue<Integer> queue = new ArrayDeque<> ();
boolean[] visited = new boolean[N+1];
queue.offer(num);
visited[num] = true;
int cnt = 0;
while (!queue.isEmpty()) {
int now = queue.poll();
for (int i=1; i<=N; i++) {
if (now==i || matrix[now][i] == 0 || visited[i] == true) continue;
queue.offer(i);
visited[i] = true;
cnt++;
}
}
return cnt;
}
}
4. ์ฌ๋ด
๊ทธ๋ํ ๋ฌธ์ ๋ ์ฌ๋ฐ๋ ๊ฒ ๊ฐ๋ค.
'Algorithm > Programmers' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Programmers] ์ ํ๋ฒํธ ๋ชฉ๋ก - Java (0) | 2023.10.04 |
---|---|
[Programmers] ๋ชจ์์ฌ์ - Java (0) | 2023.10.03 |
[Programmers] ํผ๋ก๋ - Java (0) | 2023.09.20 |
[Programmers] ์์์ฐพ๊ธฐ (level 2) - Java (1) | 2023.09.18 |
[Programmers] ์์์ฐพ๊ธฐ(Level 1) - Java (0) | 2023.09.16 |