๋ฌธ์ (์ถ์ฒ: https://www.acmicpc.net/problem/15242)
< Knight >
๋ฌธ์ ํ์ด
bfs ์๊ณ ๋ฆฌ์ฆ์ ํ์ฉํ๋ค.
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 _15242_ { // Knight
static int dx[] = { -2, -2, -1, 1, 2, 2, 1, -1 };
static int dy[] = { -1, 1, 2, 2, 1, -1, -2, -2 };
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String start = bf.readLine();
String end = bf.readLine();
int x1 = 8 - (start.charAt(1)-'0');
int y1 = start.charAt(0) - 'a';
int x2 = 8 - (end.charAt(1)-'0');
int y2 = end.charAt(0) - 'a';
if (x1 == x2 && y1 == y2) {
System.out.println(0);
} else {
System.out.println(bfs(x1, y1, x2, y2));
}
}
private static int bfs(int x1, int y1, int x2, int y2) {
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[] { x1, y1, 0 });
boolean visited[][] = new boolean[8][8];
visited[x1][y1] = true;
while (!queue.isEmpty()) {
int temp[] = queue.poll();
for (int i = 0; i < 8; i++) {
int x = temp[0] + dx[i];
int y = temp[1] + dy[i];
if (x >= 0 && x < 8 && y >= 0 && y < 8 && !visited[x][y]) {
if (x == x2 && y == y2) {
return temp[2] + 1;
}
visited[x][y] = true;
queue.add(new int[] { x, y, temp[2] + 1 });
}
}
}
return -1;
}
}
๋ณ์)
start, end : ์ถ๋ฐ ์์น, ๋์ฐฉ ์์น
x1, y1, x2, y2 : ์ถ๋ฐ ์์น, ๋์ฐฉ ์์น๋ฅผ ์ข์๋จ์ ๋ง์ถฐ ๋ณ๊ฒฝ
์ถ๋ฐ ์์น์ ๋์ฐฉ ์์น๋ฅผ ์ ๋ ฅ๋ฐ๋๋ค. ํ์ฌ ์ ๋ ฅ๋ ์์น๋ ์ขํ๋จ ๊ธฐ์ค์ด๋ฏ๋ก ์ข์๋จ์ ๋ง์ถฐ ๋ณ๊ฒฝํ์ฌ x1, y1, x2, y2์ ์ ์ฅํ๋ค. ์ถ๋ฐ ์์น์ ๋์ฐฉ ์์น๊ฐ ๊ฐ๋ค๋ฉด 0์ ์ถ๋ ฅํ๊ณ ๊ฐ์ง ์๋ค๋ฉด bfs ํจ์๋ฅผ ํธ์ถํ๋ค.
bfs(int x1, int y1, int x2, int y2)
Queue์ ์์ ์์น์ ์ด๋ ํ์๋ฅผ ์ ์ฅํ๋ฉฐ ์์ ์์น๋ฅผ ๋ฐฉ๋ฌธ์ฒ๋ฆฌํ๋ค. Queue๊ฐ ๋น ๋๊น์ง ๋ค์ ๊ณผ์ ์ ๋ฐ๋ณตํ๋ค.
1) Queue poll
2) 8๋ฐฉํฅ์ผ๋ก ํ์ ํ ๋ฐฐ์ด ๋ฒ์ ์์ด๋ฉฐ ์์ง ๋ฐฉ๋ฌธํ์ง ์์ ๊ณณ์ด๋ผ๋ฉด ๋ฐฉ๋ฌธ ํ์ ๋ฐ Queue์ ์ถ๊ฐ. ๋ง์ฝ ์ด๋ ์์น๊ฐ ๋์ฐฉ ์์น๋ผ๋ฉด temp[2]+1์ ๋ฐํํ๋ค.

'๐Algorithm > ๐ฅBaekjoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Baekjoon] 6601_Knight Moves (0) | 2024.11.19 |
---|---|
[Baekjoon] 6798_Knight Hop (0) | 2024.11.18 |
[Baekjoon] 16390_Shebaโs Amoebas (0) | 2024.11.14 |
[Baekjoon] 5931_Cow Beauty Pageant (0) | 2024.11.13 |
[Baekjoon] 8061_Bitmap (0) | 2024.11.12 |