资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
一个8×8的棋盘上有一个马初始位置为(a,b),他想跳到(c,d),问是否可以?如果可以,最少要跳几步?
输入格式
一行四个数字a,b,c,d。
输出格式
如果跳不到,输出-1;否则输出最少跳到的步数。
样例输入
1 1 2 3
样例输出
1
数据规模和约定
0<a,b,c,d≤8且都是整数。
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import javax.management.Query;
public class Main {
static int[][] dir = new int[][]{{-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {1, 2}, {1, -2}, {2, 1}, {2, -1}};//马移动的8个方位
static int map[][] = new int[15][15];
static int sx,sy,fx,fy;
static boolean vis[][] = new boolean[15][15];
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
sx = scanner.nextInt();
sy = scanner.nextInt();
fx = scanner.nextInt();
fy = scanner.nextInt();
bfs(sx,sy);
System.out.println(map[fx][fy]);
}
public static void bfs(int x,int y) {
vis[x][y] = true;
Queue<node> queue = new LinkedList<node>();
queue.offer(new node(x,y));
int step = 0;
map[x][y] = step;
while(!queue.isEmpty()) {
node now = queue.poll();
step = map[now.getX()][now.getY()]+1;
for(int i=0;i<8;i++) {
int nx = now.getX()+dir[i][0];
int ny = now.getY()+dir[i][1];
if(inMap(nx, ny)&&!vis[nx][ny]) {
vis[nx][ny] = true;
map[nx][ny] = step;
queue.offer(new node(nx, ny));
}
}
queue.poll();
}
}
public static boolean inMap(int x,int y) {
return x>=1&&x<=8&&y>=1&&y<=8;
}
}
class node{
private int x;
private int y;
public node(int x,int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}