728x90
16948번: 데스 나이트
게임을 좋아하는 큐브러버는 체스에서 사용할 새로운 말 "데스 나이트"를 만들었다. 데스 나이트가 있는 곳이 (r, c)라면, (r-2, c-1), (r-2, c+1), (r, c-2), (r, c+2), (r+2, c-1), (r+2, c+1)로 이동할 수 있다. 크
www.acmicpc.net
package 백준renew;
import java.io.*;
import java.util.*;
public class 실버1_16948_데스나이트 {
static int goX[] = {-2, -2, 0, 0, 2, 2};
static int goY[] = {-1, 1, -2, 2, -1, 1};
static int N, ans;
static boolean visited[][];
static int startX, startY, endX, endY;
static class Jump{
int x;
int y;
int cnt;
Jump(int x, int y, int cnt){
this.x = x;
this.y = y;
this.cnt = cnt;
}
}
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringBuilder sb = new StringBuilder();
N = Integer.parseInt(br.readLine());
ans = 0;
StringTokenizer st = new StringTokenizer(br.readLine());
startX = Integer.parseInt(st.nextToken());
startY = Integer.parseInt(st.nextToken());
endX = Integer.parseInt(st.nextToken());
endY = Integer.parseInt(st.nextToken());
visited = new boolean[N][N];
BFS(startX, startY);
if(ans == 0) {
sb.append(-1);
}else {
sb.append(ans);
}
bw.write(sb.toString());
bw.flush();
bw.close();
}
static void BFS(int x, int y) {
Queue<Jump> queue = new LinkedList<>();
queue.offer(new Jump(x, y, 0));
visited[x][y] = true;
while(!queue.isEmpty()) {
Jump j = queue.poll();
if(j.x == endX && j.y == endY) {
ans = j.cnt;
return;
}
for(int i=0; i<6; i++) {
int newX = j.x + goX[i];
int newY = j.y + goY[i];
if(newX < 0 || newX >= N || newY < 0 || newY >= N || visited[newX][newY]) {
continue;
}
queue.offer(new Jump(newX, newY, j.cnt+1));
visited[newX][newY] = true;
}
}
}
}
728x90
'코테 > Algorithm' 카테고리의 다른 글
[BOJ] 10815: 숫자 카드 (JAVA) (0) | 2024.03.11 |
---|---|
[BOJ] 1920: 수 찾기 (JAVA) (0) | 2024.03.11 |
[BOJ] 9655: 돌 게임 (JAVA) (0) | 2024.03.09 |
[BOJ] 1343: 폴리오미노 (JAVA) (0) | 2024.03.08 |
[BOJ] 19638: 센티와 마법의 뿅망치 (JAVA) (0) | 2024.03.08 |