문제:
https://www.acmicpc.net/problem/7562
7562번: 나이트의 이동
체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수
www.acmicpc.net
코드:
import java.util.*;
public class Main {
public static int [] dx = {-2,-1,1,2,2,1,-1,-2};
public static int [] dy = {1,2,2,1,-1,-2,-2,-1};
public static int t,n;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
t = sc.nextInt(); // 테스트케이스
while(t --> 0) {
n = sc.nextInt(); // 가로,세로
int [][] dist = new int[n][n];
Queue<Pos> q = new LinkedList<>();
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
dist[i][j] = -1; // 모두 -1 초기화 (거리 설정 위함)
}
}
int x1 = sc.nextInt(); // 시작지
int y1 = sc.nextInt();
dist[x1][y1] = 0; // 시작지 거리는 0
q.add(new Pos(x1,y1));
int x2 = sc.nextInt(); // 목적지
int y2 = sc.nextInt();
while(!q.isEmpty()) {
Pos cur = q.poll();
for(int dir = 0;dir<8;dir++) {
int nx = cur.x+dx[dir];
int ny = cur.y+dy[dir];
if(nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
if(dist[nx][ny] >= 0) continue; // 거리가 이미 주어지면 continue
dist[nx][ny] = dist[cur.x][cur.y]+1;
q.add(new Pos(nx,ny));
}
}
/*
// 확인용
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
System.out.print(dist[i][j]+" ");
}
System.out.println();
}
*/
System.out.println(dist[x2][y2]);
}
}
}
class Pos{
int x;
int y;
Pos(int x,int y){
this.x = x;
this.y= y;
}
}
'Java > 백준' 카테고리의 다른 글
[Java][2583] 영역 구하기 (0) | 2022.08.19 |
---|---|
[Java][6593] 상범 빌딩 (0) | 2022.08.19 |
[Java][10026] 적록색약 (0) | 2022.08.17 |
[Java][6588] 골드바흐의 추측 (1) | 2022.08.14 |
[Java][2178] 미로 탐색 (1) | 2022.08.13 |