(dfs,不是bfs)
#include <bits/stdc++.h>
using namespace std;
long long a,b,c,d,e,f,g,h,i[1000][1000],j[8][2]={{-2,1},{-2,-1},{2,-1},{2,1},{-1,-2},{1,-2},{-1,2},{1,-2}},k[1000][1000];
void dfs(long long e,long long f,long long c)
{
if(k[e][f]==0)
{
if(i[e][f]==0)
{
if((e!=c||f!=d)&&i[e][f]==0)
{
i[e][f]=c;
}
i[e][f]=min(i[e][f],c);
}
for(g=0;g<=7;g++)
{
if(j[g][0]+e>=0&&j[g][0]+e<a&&j[g][1]+h>=0&&j[g][1]+h<b)
{
k[e][f]=1;
dfs(j[g][0]+e,j[g][1]+f,c+1);
}
}
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("P1443 马的遍历.in","r",stdin);
//freopen("P1443 马的遍历.out","w",stdout);
#endif
cin>>a>>b>>c>>d;
dfs(c-1,d-1,0);
for(e=0;e<a;e++)
{
for(f=0;f<b;f++)
{
if((e!=c-1||f!=d-1)&&i[e][f]==0)
{
cout<<-1<<" ";
continue;
}
cout<<i[e][f]<<" ";
}
cout<<endl;
}
return 0;
}
调试时刚进入dfs函数就错误
连续10个回复第一次试验证码错误了。