题意是:给定一个8*8的棋盘然后给你起点和终点的坐标让你求骑士(也就是中国象棋中的马,只不过没有拌腿的限制)从起点走到终点的最短距离
思路就是用BFS从起点开始按照骑士的走法遍历棋盘,知道走到终点。
//注意起点和终点在一起的情况
import java.util.ArrayList;
import java.util.Scanner;
//BFS求解最小距离
public class Main {
static int inc[][]={{-1,2},{1,2},{2,1},{2,-1},{-2,-1},{-1,-2},{1,-2},{-2,1}};
static int map[][]=new int[9][9];
static boolean mark[][]=new boolean[9][9];
static String start,end;
class Node
{
int x,y;
int num;
Node(int x,int y)
{
this.x=x;
this.y=y;
}
}
void run() {
Scanner in=new Scanner(System.in);
while(in.hasNext())
{
start=in.next();
end=in.next();
int x1=start.charAt(0)-'a'+1;
int y1=start.charAt(1)-'0';
int x2=end.charAt(0)-'a'+1;
int y2=end.charAt(1)-'0';
Node star=new Node(x1,y1);
//注意终点和起点在一起的时候
if(x1==x2&&y1==y2)
{
System.out.println("To get from "+start+" to "+end+" takes "+0+" knight moves.");
}else
{
for(int i=1;i<=8;i++)
{
for(int j=1;j<=8;j++)
{
if(i==x1&&j==y1)
map[i][j]=1;
else if(i==x2&&j==y2)
map[i][j]=2;
else
map[i][j]=0;
}
}
BFS(star);
}
}
}
void BFS(Node star)
{
for(int i=1;i<=8;i++)
for(int j=1;j<=8;j++)
mark[i][j]=false;
ArrayList<Node> lis=new ArrayList<Node>();
int ans=0;
star.num=0;
Node cur,next;
int a=star.x;
int b=star.y;
lis.add(star);
mark[a][b]=true;
while(!lis.isEmpty())
{
cur=lis.remove(0);
for(int i=0;i<8;i++)
{
int t1=cur.x+inc[i][0];
int t2=cur.y+inc[i][1];
next=new Node(t1,t2);
if(t1>=1&&t1<=8&&t2>=1&&t2<=8&&!mark[t1][t2])
{
int flag=map[t1][t2];
next.num=cur.num+1;
mark[t1][t2]=true;
lis.add(next);
if(flag==2)
{
ans=next.num;
System.out.println("To get from "+start+" to "+end+" takes "+ans+" knight moves.");
return;
}
}
}
}
}
public static void main(String[] args) {
new Main().run();
}
}