[Baekjoon] 1331_๋์ดํธ ํฌ์ด
๋ฌธ์ (์ถ์ฒ: https://www.acmicpc.net/problem/1331)
< ๋์ดํธ ํฌ์ด >
๋ฌธ์ ํ์ด
๋์ดํธ๊ฐ ๊ฒฝ๋ก๋ก ์ด๋ ๊ฐ๋ฅํ์ง ํ๋จํ๋ค. ๋ชจ๋ ์นธ์ ์ ํํ ํ ๋ฒ์ฉ ๋ฐฉ๋ฌธํด์ผ ํ๋ฏ๋ก ์ด๋ฏธ ๋ฐฉ๋ฌธํ ๊ณณ์๋ ๊ฐ ์ ์๋ค.
my solution (Java)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
public class _1331_ { // ๋์ดํธ ํฌ์ด
static Queue<int[]> queue;
static boolean arr[][];
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
arr = new boolean[6][6];
int startX = 0, startY = 0;
queue = new LinkedList<>();
for (int i = 0; i < 36; i++) {
String str = bf.readLine();
int x = 0;
int y = 6 - (str.charAt(1) - '0');
if (str.charAt(0) == 'A') {
x = 0;
} else if (str.charAt(0) == 'B') {
x = 1;
} else if (str.charAt(0) == 'C') {
x = 2;
} else if (str.charAt(0) == 'D') {
x = 3;
} else if (str.charAt(0) == 'E') {
x = 4;
} else if (str.charAt(0) == 'F') {
x = 5;
}
if (i == 0) {
startX = x;
startY = y;
}
queue.add(new int[] { x, y });
}
queue.add(new int[] { startX, startY });
if (check(queue)) {
System.out.println("Valid");
} else {
System.out.println("Invalid");
}
}
private static boolean check(Queue<int[]> queue) {
int dx[] = { -1, -2, -2, -1, 1, 2, 2, 1 };
int dy[] = { -2, -1, 1, 2, 2, 1, -1, -2 };
int now[] = queue.poll();
boolean flag = false;
while (!queue.isEmpty()) {
for (int i = 0; i < 8; i++) {
int x = now[0] + dx[i];
int y = now[1] + dy[i];
if (queue.peek()[0] == x && queue.peek()[1] == y) {
if (arr[x][y]) {
return false;
}
arr[x][y] = true;
flag = true;
now = queue.poll();
break;
}
}
if (!flag) {
return false;
}
flag = false;
}
return true;
}
}
๋ณ์)
arr : ์ฒด์คํ ๋ฐฉ๋ฌธ ์ฌ๋ถ
startX, startY : ์์ ์์น
queue : ๋์ดํธ ๋ฐฉ๋ฌธ ๊ฒฝ๋ก
str : ๋ฐฉ๋ฌธ ์์น
x, y : ๋ฐฉ๋ฌธ ์์น๋ฅผ ์ซ์๋ก ๋ณํ
36 ๊ฐ์ค์ ๊ฑธ์ณ ๋์ดํธ์ ๋ฐฉ๋ฌธ ์์น๋ฅผ ์ ๋ ฅ๋ฐ๋๋ค. A-F๋ฅผ ๊ฐ 0-5๋ก ์นํํ๊ณ 1-6์ 5-0์ผ๋ก ์นํํ์ฌ queue์ ์ ์ฅํ๋ค. ์ฒซ ๋ฒ์งธ ๋ฐฉ๋ฌธ ์์น๋ฅผ ๊ธฐ์ตํด ๋๋ค ๋ง์ง๋ง์ ๋ค์ queue์ ์ถ๊ฐํ๋ค. ๊ทธ ํ check ํจ์๋ฅผ ํตํด ๋์ดํธ์ ๊ฒฝ๋ก๋ฅผ ํ์ธํ๊ณ ์ฌ๋ฐ๋ฅธ ๊ฒ์ด๋ฉด Valid๋ฅผ ์ฌ๋ฐ๋ฅด์ง ์์ ๊ฒฝ๋ก๋ฉด Invalid๋ฅผ ์ถ๋ ฅํ๋ค.
check (Queue <int []> queue)
queue์์ poll ํ์ฌ ์์ ์์น๋ฅผ now์ ์ ์ฅํ๋ค. queue๊ฐ ๋น ๋๊น์ง ๋ค์ ๊ณผ์ ์ ๋ฐ๋ณตํ๋ค.
1) ๋์ดํธ๊ฐ ์ด๋ํ ์ ์๋ 8๋ฐฉํฅ์ ์ขํ๋ฅผ ๊ตฌํ ํ ๊ทธ ์ขํ๊ฐ queue์ peek ๊ฐ๊ณผ ์ผ์นํ๋์ง ํ์ธํ๋ค.
2) ์ผ์นํ๋ฉด ๋ฐฉ๋ฌธ ์ฌ๋ถ๋ฅผ ์ดํด๋ณธ๋ค. ์ด๋ฏธ ๋ฐฉ๋ฌธํ ๊ณณ์ด๋ผ๋ฉด false๋ฅผ ๋ฐํํ๋ค. ์์ง ๋ฐฉ๋ฌธํ์ง ์์ ๊ณณ์ด๋ผ๋ฉด ๋ฐฉ๋ฌธ ํ์ ํ queue์์ poll ํ ๊ฐ์ผ๋ก ํ์ฌ ์์น๋ฅผ ์ ๋ฐ์ดํธํ ํ ๋ค์ 1)๋ก ๋์๊ฐ๋ค.
3) 8๋ฐฉํฅ ์ขํ ๋ชจ๋ queue์ peek ๊ฐ๊ณผ ์ผ์นํ์ง ์๋ค๋ฉด ์ฌ๋ฐ๋ฅด์ง ์์ ๋์ดํธ ๊ฒฝ๋ก์ด๋ฏ๋ก false๋ฅผ ๋ฐํํ๋ค.
queue๊ฐ ๋น์๋ค๋ฉด ๋์ดํธ์ ์ฌ๋ฐ๋ฅธ ๊ฒฝ๋ก์ด๋ฏ๋ก true๋ฅผ ๋ฐํํ๋ค.
