资源限制
时间限制: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且都是整数。
解题(使用C++解题)
思路:宽度搜索切入
include <iostream>
using namespace std;
const int N=30;
int st[N][N];
int a,b,c,d;
int count=1000000;//设置count计算次数
int up[8]={1,2,2,1,-1,-2,-2,-1};
int dw[8]={2,1,-1,-2,-2,-1,1,2};
void dfs(int m,int n,int u){
if(u>10){
return;
}
//cout<<m<<" "<<n<<endl;
for(int i=0;i<8;i++){
if(m+up[i]<1||m+up[i]>8||n+dw[i]>8||n+dw[i]<1)continue;
if(st[m+up[i]][n+dw[i]]==2){
if(u<count)count=u;
}
else if(st[m+up[i]][n+dw[i]]==0){
dfs(m+up[i],n+dw[i],u+1);
}
}
}
int main(){
cin>>a>>b>>c>>d;
st[a][b]=0;
st[c][d]=2;
if(st[a][b]==2){
cout<<0;
return 0;
}
dfs(a,b,1);
if(count==1000000)cout<<-1;//如果没有找到,则输出-1
else cout<<count;
return 0;
}