试题 算法训练 跳马

资源限制
时间限制: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;
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值