๋ฌธ์ (์ถ์ฒ: https://www.acmicpc.net/problem/32076)
< Easy as ABC >
๋ฌธ์ ํ์ด
์ฌ์ ์ ์ผ๋ก ๊ฐ์ฅ ์์ ์๋ ๊ฐ์ฅ ์์ ๊ธธ์ด์ ๋จ์ด๋ฅผ ์ฐพ๊ธฐ ์ํด์๋ ๋จ์ด ์์์ด A, B, C ์์ด์ด์ผ ํ๋ค. ๋ง์ฝ 3x3 ๊ทธ๋ฆฌ๋ ๋ด์ A๊ฐ ์๋ค๋ฉด ๋ฌด์กฐ๊ฑด A๋ก ์์ํด์ผ ์ฌ์ ์ ์ผ๋ก ๊ฐ์ฅ ์์ ์๋ ๋จ์ด๋ฅผ ๋ง๋ค ์ ์๊ธฐ ๋๋ฌธ์ด๋ค. A๊ฐ ์๋ค๋ฉด B๋ก ์์ํ๊ณ , B๊ฐ ์๋ค๋ฉด C๋ก ์์ํด์ผ ํ๋ค. 8๋ฐฉํฅ์ผ๋ก ์ด๋ํ๋ฉด์ ๊ตฌํ ์ ์๋ ๋จ์ด๋ฅผ ๋ชจ๋ ๊ตฌํด ์ ๋ ฌ ํ ๋งจ ์์ ์๋ ๊ฐ์ด ์ ๋ต์ด๋ค.
my solution (Java)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.PriorityQueue;
public class _32076_ { // Easy as ABC
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
char arr[][] = new char[3][3];
PriorityQueue<int[]> queue = new PriorityQueue<>(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[2] - o2[2];
}
});
for (int i = 0; i < 3; i++) {
String str = bf.readLine();
for (int j = 0; j < 3; j++) {
arr[i][j] = str.charAt(j);
queue.add(new int[] { i, j, arr[i][j] - '0' });
}
}
int num = queue.peek()[2];
int dx[] = { -1, -1, -1, 0, 1, 1, 1, 0 };
int dy[] = { -1, 0, 1, 1, 1, 0, -1, -1 };
ArrayList<String> list = new ArrayList<>();
while (!queue.isEmpty() && num == queue.peek()[2]) {
int temp[] = queue.poll();
boolean visited[][] = new boolean[3][3];
visited[temp[0]][temp[1]] = true;
for (int i = 0; i < 8; i++) {
String str = Character.toString((char) (temp[2] + '0'));
int x = temp[0] + dx[i];
int y = temp[1] + dy[i];
if (x >= 0 && x < 3 && y >= 0 && y < 3 && !visited[x][y]) {
str = str + arr[x][y];
visited[x][y] = true;
for (int j = 0; j < 8; j++) {
int x2 = x + dx[j];
int y2 = y + dy[j];
if (x2 >= 0 && x2 < 3 && y2 >= 0 && y2 < 3 && !visited[x2][y2]) {
String str2 = str + arr[x2][y2];
list.add(str2);
}
}
}
}
}
Collections.sort(list);
System.out.println(list.get(0));
}
}
๋ณ์)
arr : ๊ทธ๋ฆฌ๋
queue : ์ฐ์ ์์ ํ
num : ์์ ๊ฐ
dx, dy : ์ด๋ํ ์ ์๋ 8๋ฐฉํฅ
list : ๋ง๋ค ์ ์๋ ๋จ์ด
visited : ๋ฐฉ๋ฌธ ์ฌ๋ถ
๋ฐฐ์ด arr์ ์ ๋ ฅ๋ฐ์ ๊ฐ์ ์ ์ฅํ๋ฉฐ ์ฐ์ ์์ ํ์ [์์น, ๋ฌธ์]๋ฅผ ์ ์ฅํฉ๋๋ค. ์ด๋, ์ฐ์ ์์ ํ๋ ๋ฌธ์๋ฅผ ๊ธฐ์ค์ผ๋ก ์ค๋ฆ์ฐจ์์ผ๋ก ์ฐ์ ์์๋ฅผ ๊ฐ์ง๋๋ค. ์ฐ์ ์์ ํ์ A, B, C ์์๋ก ์ ๋ ฌ๋์ด ์๊ธฐ ๋๋ฌธ์ ํ์ peek() ๊ฐ์ ๊ธฐ์ค์ผ๋ก ์ผ์นํ๋ ๊ฐ์ ๊ฐ์ง ์์น๋ฅผ ๊ธฐ์ค์ผ๋ก ๋ค์ ๊ณผ์ ์ ๋ฐ๋ณตํฉ๋๋ค.
1) queue.poll()
2) 8๋ฐฉํฅ์ผ๋ก ์ด๋ํ์ฌ ๊ทธ๋ฆฌ๋ ๋ฒ์ ๋ด๊ณ ์์ง ๋ฐฉ๋ฌธํ์ง ์์ ๊ณณ์ด๋ผ๋ฉด ๋ฌธ์ ์ถ๊ฐ ๋ฐ ๋ฐฉ๋ฌธ ํ์
3) ๊ทธ ์์น์์ ๋ค์ 8๋ฐฉํฅ์ผ๋ก ์ด๋ํ์ฌ ๊ทธ๋ฆฌ๋ ๋ฒ์ ๋ด๊ณ ์์ง ๋ฐฉ๋ฌธํ์ง ์์ ๊ณณ์ด๋ผ๋ฉด ๋ฌธ์ ์ถ๊ฐ ๋ฐ ArrayList์ ์ถ๊ฐ
์ต์ข ArrayList๋ฅผ ์ ๋ ฌ ํ ๋งจ ์์ ์๋ ๊ฐ์ ์ถ๋ ฅํฉ๋๋ค.
'๐Algorithm > ๐ฅBaekjoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Baekjoon] 14210_Kartomat (0) | 2025.07.14 |
---|---|
[Baekjoon] 27060_Vertical Histogram (2) | 2025.07.11 |
[Baekjoon] 3518_๊ณต๋ฐฑ์ ๋น-์นธ (1) | 2025.07.09 |
[Baekjoon] 16300_H to O (2) | 2025.07.08 |
[Baekjoon] 26043_์๋น ๋ฉ๋ด (3) | 2025.07.07 |