์ค๋์ ํ์ต ํค์๋
๋ฌธ์ - ๋ฏธ๋ค๋ฌ
๋์ดํธ์ ์ด๋
ํ์ด
import java.util.*;
class Main {
static int testCase;
static int l;
static int[][] board;
static boolean[][] visited;
static int[] dx = {1, 2, 2, 1, -1, -2, -2, -1};
static int[] dy = {2, 1, -1, -2, -2, -1, 1, 2};
static void bfs(int startX, int startY, int targetX, int targetY) {
Queue<int[]> q = new LinkedList<>();
q.offer(new int[]{startX, startY});
visited[startX][startY] = true;
while (!q.isEmpty()) {
int[] current = q.poll();
int curX = current[0];
int curY = current[1];
if (curX == targetX && curY == targetY) { // ํ์ฌ์์น์ ๋ชฉํ์์น๊ฐ ๊ฐ๋ค๋ฉด ํจ์ ์ข
๋ฃ
return;
}
for (int i = 0; i < 8; i++) {
int nextX = curX + dx[i];
int nextY = curY + dy[i];
// ์ฒด์ค(board)์ ๋ฒ์๋ฅผ ๋ฒ์ด๋์ง ์๊ณ , ๋ฐฉ๋ฌธํ ์ ์ด ์๋ค๋ฉด, ๋ฐฉ๋ฌธ์ฒ๋ฆฌ ํด์ฃผ๊ณ ์ด์ ๊ฐ๋ณด๋ค ๊ฐ์ 1 ์ฆ๊ฐ์ํต๋๋ค.
if (nextX >= 0 && nextX < l && nextY >= 0 && nextY < l && !visited[nextX][nextY]) {
q.offer(new int[]{nextX, nextY});
visited[nextX][nextY] = true;
board[nextX][nextY] = board[curX][curY] + 1;
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
testCase = sc.nextInt();
while (testCase != 0) {
testCase--;
l = sc.nextInt();
board = new int[l][l];
visited = new boolean[l][l];
int currentX = sc.nextInt();
int currentY = sc.nextInt();
int targetX = sc.nextInt();
int targetY = sc.nextInt();
bfs(currentX, currentY, targetX, targetY);
System.out.println(board[targetX][targetY]);
}
}
}
- BFS๋ฅผ ์์ฉํด์ ํ์ดํ๋ฉด ๋๋ ๋ฌธ์ ์
๋๋ค.
- ์์ฉํ ๋ถ๋ถ์ ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
- ํ์ฌ ์์น์ ๋ชฉํ ์์น๊ฐ ๊ฐ๋ค๋ฉด, BFS๋ฅผ ์ข
๋ฃํ๋ ์กฐ๊ฑด์ ์ถ๊ฐ
- ์ฒด์ค์ ์์น๋ฅผ ๋ฒ์ด๋๋ฉด ํ์ํ์ง ์๋ ์กฐ๊ฑด์ ์ถ๊ฐ