------------马的最短路径
题目描述:
一匹马在一个8*8的棋盘上走着,它的每一步恰好走成一个日字,也就是在x、y两个方向上,如果在一个方向走一步,另一个方向就走两步。假设棋盘的下标左下角是(1,1),右上角是(8,8)。给你马的最初位置(a,b)各最终位置(an,bn),请你编程求出马从最初位置到最终位置所走的最少步数。
Input
先输入一个正整数T表示有T种情况,每一种情况一行,由四个正整数组成,分别表示a、b、an、bn。
Ouput
每种情况先输出“Case :id”,id是从1开始的序号,然后输出马走的最小步数。
输入:
2
1 1 2 3
5 2 5 4
输出:
Case 1:1
Case 2:2
代码展示:
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[][] array = {{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1},{-2,1},{-1,2}};
int n = in.nextInt();
for(int i = 1; i <= n; i++){
int[][] vis = new int[9][9];
Queue<Horse> queue = new LinkedList<Horse>();
int x = in.nextInt();
int y = in.nextInt();
int endX = in.nextInt();
int endY = in.nextInt();
queue.add(new Horse(x,y,0));
while (!queue.isEmpty()){
Horse h = queue.poll();
if(h.getX()==endX && h.getY()==endY){
System.out.println("Case "+i+":"+h.getStep());
break;
}else{
for(int j = 0; j < 8; j++){
Horse hh = new Horse(h.getX()+array[j][0],h.getY()+array[j][1],h.getStep()+1);
if(hh.getX()>=1&&hh.getX()<=8&&hh.getY()>=1&&hh.getY()<=8&&vis[hh.getX()][hh.getY()]!=1){
queue.add(hh);
}
}
vis[h.getX()][h.getY()] = 1;
}
}
}
}
}
class Horse{
private int x,y,step;
public Horse(int x, int y, int step) {
this.x = x;
this.y = y;
this.step = step;
}
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;
}
public int getStep() {
return step;
}
public void setStep(int step) {
this.step = step;
}
}
注:
因为广度优先遍历与层次遍历类似,按层搜索的,先第一层、第二层…… 第n层。因为是一层一层地搜索,第一层没有,就在第二层找,第二层没有,就在第三层找…… 若在第k层找到了,说明在[0, k-1]层中都没有找到目标。所以k一定是最短的层数,即最短路。