题目描述
Luck 有一个象棋棋子“马”,它在一个 n*m 的矩阵棋盘,棋盘左上角坐标为(1,1),右下角坐
标为(n,m),它现在的位置是(
s
x
, s
y
),现在 Luck 想让它走到目标点(
e
x
, e
y
)。作为象棋棋子“马”,
它每次可以走到的方式为走一个“日”字,符合象棋规则。作为一名精通"算法设计与分析"课
的长春理工大学本科生,你希望走的步数最少,请输出最少的行走步数。
输入格式
第一行两个整数 n,m(4<=n,m<=1000),代表棋盘的大小。
第二行四个整数,
s
x
, s
y
, e
x
, e
y
,分别代表初始位置和目标点坐标。
输出格式
一行包含一个整数,代表走的最少步数。
输入样例 1
4 4
1 1 4 4
输出样例 1
2
输入样例 2
1000 1000
3 3 1000 1000
输出样例 2
666
java代码:
package asdf;
import java.util.ArrayDeque;
import java.util.Queue;
//1 1 3 1
//2
import java.util.Scanner;
public class HorseCount {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String[] size=sc.nextLine().split(" ");
int sizex=Integer.parseInt(size[0]);
int sizey=Integer.parseInt(size[1]);
String[] str=sc.nextLine().split(" ");
int x=Integer.parseInt(str[0]);
int y=Integer.parseInt(str[1]);
int desx=Integer.parseInt(str[2]);
int desy=Integer.parseInt(str[3]);
horse(x,y,desx,desy,sizex,sizey);
sc.close();
}
private static void horse(int x,int y,int desx,int desy,int sizex,int sizey) {
boolean[][] visited=new boolean[9][9];
Queue<Node> queue=new ArrayDeque<>();
int[][] axes= {{1,2},{1,-2},{2,1},{2,-1},{-1,2},{-1,-2},{-2,1},{-2,-1}};
for(int i = 1;i<=8;i++){
for(int j = 1;j<=8;j++){
visited[i][j] = false;
}
}
Node node=new Node(x,y,0);
visited[x][y] = true;
queue.offer(node);
while(!queue.isEmpty()) {
Node front=queue.poll();
int a=front.x;
int b=front.y;
int step=front.step;
if(a==desx&&b==desy) {
System.out.println(step);
}else {
for(int i=0;i<axes.length;i++) {
int hx=a+axes[i][0];
int hy=b+axes[i][1];
int hstep=step+1;
Node ho=new Node(hx,hy,hstep);;
if(ho.x>=1&&ho.x<=sizex&&ho.y>=1&&ho.y<=sizey&&visited[ho.x][ho.y]==false) {
queue.offer(ho);
visited[ho.x][ho.y]=true;
}
}
}
}
}
}
class Node{
public int x;
public int y;
public int step;
public Node(int x,int y,int step){
this.x = x;
this.y = y;
this.step=step;
}
}
//数组大小可以手动设置,怕越界的话可以设置的大一点。 boolean[][] visited=new boolean[9][9];比如9可以设置成1000