
https://www.acmicpc.net/problem/24445
๐ ์๋ฐ(Java)๋ก ํธ๋ ๋๋น ์ฐ์ ํ์(BFS) - ๋ฐฑ์ค 24445 ๋ฌธ์ ํ์ด ๐
๐ ๋ฌธ์ ๊ฐ์
์ด ๋ฌธ์ ๋ ๋ฐฑ์ค 24445๋ฒ - ์๊ณ ๋ฆฌ์ฆ ์์
- ๋๋น ์ฐ์ ํ์ 2 ๋ฌธ์ ์
๋๋ค.
๊ธฐ๋ณธ์ ์ธ BFS(๋๋น ์ฐ์ ํ์) ๊ณผ์ ์ 24444๋ฒ๊ณผ ๋์ผํ์ง๋ง,
์ด๋ฒ์๋ ์ ์ ๋ฐฉ๋ฌธ ์์๋ฅผ ๋ด๋ฆผ์ฐจ์์ผ๋ก ์ ๋ ฌํด์ผ ํฉ๋๋ค.
๐ก ์์ ์ ๋ ฅ
5 5 1
1 4
1 2
2 3
2 4
3 4
๐ก ์์ ์ถ๋ ฅ
1
4
3
2
5
โก BFS ํ์ ์ ์ ์ ์ ํฐ ์ซ์๋ถํฐ ๋ฐฉ๋ฌธํ๋๋ก ๊ตฌํํด์ผ ํฉ๋๋ค.
๐ ์๊ณ ๋ฆฌ์ฆ ์ ๊ทผ ๋ฐฉ์
์ด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๋ ๋ฐฉ์์ 24444๋ฒ ๋ฌธ์ ์ ๋์ผํ์ง๋ง,
๊ฐ ์ ์ ์ ์ธ์ ๋ฆฌ์คํธ๋ฅผ ๋ด๋ฆผ์ฐจ์(Collections.reverseOrder())์ผ๋ก ์ ๋ ฌํด์ผ ํฉ๋๋ค.
๐น Java ์ฝ๋ ํด์ค
import java.io.*;
import java.util.*;
public class b24445 {
static int N, M, R;
static ArrayList<Integer>[] list;
static boolean[] isVisited;
static Queue<Integer> q = new ArrayDeque<>();
static int[] result;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = stoInt(st.nextToken());
M = stoInt(st.nextToken());
R = stoInt(st.nextToken());
isVisited = new boolean[N + 1];
result = new int[N + 1];
list = new ArrayList[N + 1];
inputAndSort(br); // ์
๋ ฅ ๋ฐ ์ ๋ ฌ ์ฒ๋ฆฌ
BFS(R); // BFS ์คํ
printResult(); // ๊ฒฐ๊ณผ ์ถ๋ ฅ
}
// ์
๋ ฅ ๋ฐ ๋ด๋ฆผ์ฐจ์ ์ ๋ ฌ
private static void inputAndSort(BufferedReader br) throws IOException {
for (int i = 0; i <= N; i++) {
list[i] = new ArrayList<>();
}
for (int i = 0; i < M; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int a = stoInt(st.nextToken());
int b = stoInt(st.nextToken());
list[a].add(b);
list[b].add(a);
}
// ๋ด๋ฆผ์ฐจ์ ์ ๋ ฌ (ํฐ ์ซ์๋ถํฐ ๋ฐฉ๋ฌธ)
for (int i = 0; i <= N; i++) {
list[i].sort(Collections.reverseOrder());
}
}
static int stoInt(String s) {
return Integer.parseInt(s);
}
// BFS ๊ตฌํ
static void BFS(int r) {
int count = 1;
q.add(r);
isVisited[r] = true;
while (!q.isEmpty()) {
int now = q.poll();
result[now] = count++;
for (int num : list[now]) {
if (!isVisited[num]) {
q.add(num);
isVisited[num] = true;
}
}
}
}
// ๊ฒฐ๊ณผ ์ถ๋ ฅ
private static void printResult() {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= N; i++) {
sb.append(result[i]).append("\n");
}
System.out.println(sb);
}
}
๐ฅ ํต์ฌ ์์ฝ
โ
BFS ๋ฐฉ์์ ๋์ผํ์ง๋ง, ์ ์ ์ ๋ ฌ ๋ฐฉ์๋ง ๋ค๋ฆ
โ
24444๋ฒ(์ค๋ฆ์ฐจ์ ์ ๋ ฌ) โ Collections.sort() ์ฌ์ฉ
โ
24445๋ฒ(๋ด๋ฆผ์ฐจ์ ์ ๋ ฌ) โ Collections.sort(Collections.reverseOrder()) ์ฌ์ฉ
์ด ๊ธ์ด ๋์์ด ๋์
จ๋ค๋ฉด ์ข์์์ ๊ณต์ ๋ถํ๋๋ฆฝ๋๋ค! ๐
'Algorithm & Data Structures > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
b.9370 ๋ฏธํ์ธ ๋์ฐฉ์ง (0) | 2025.03.15 |
---|---|
b.1707 ์ด๋ถ ๊ทธ๋ํ (0) | 2025.03.12 |
b24444. ์๊ณ ๋ฆฌ์ฆ ์์ - ๋๋น ์ฐ์ ํ์ 1 (0) | 2025.03.04 |
b24480. ์๊ณ ๋ฆฌ์ฆ ์์ - ๊น์ด ์ฐ์ ํ์ 2 (0) | 2025.03.01 |
b3015. ์ค์์์ค ์ฌ๊ฒฐํฉ (0) | 2025.02.25 |