马从起始位置,走到目标位置,最少需要的步数。
例如:输入1 1 3 1,输出为2。(其中,1 1为起始位置,3 1为目标位置)
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[] 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);
sc.close();
}
private static void horse(int x,int y,int desx,int desy) {
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<=8&&ho.y>=1&&ho.y<=8&&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;
}
}