Horse traversal
Idea: Search on the map according to the direction the horse is walking to find the number of steps at each point.
#include <iostream>
#include <stdio.h>
using namespace std;
int n,m,map[401][401]={
0},book[401][401]={
0};
struct node{
int x;
int y;
int step;
};
int nest[8][2]={
{
2,1},{
-2,1},{
2,-1},{
-2,-1},{
1,2},{
-1,2},{
1,-2},{
-1,-2}};
node queue[160001];
int main()
{
int i,j,head,tail,a,b,tx,ty;
cin>>n>>m>>a>>b;
head=1;
tail=1;
queue[tail].x=a;
queue[tail].y=b;
queue[tail].step=0;
book[a][b]=1;
tail++;
while(head!=tail)
{
for(i=0;i<8;i++)
{
tx=queue[head].x+nest[i][0];
ty=queue[head].y+nest[i][1];
if(tx>n||ty>m||tx<1||ty<1)
{
continue;
}
if(book[tx][ty]==0)
{
queue[tail].x=tx;
queue[tail].y=ty;
queue[tail].step=queue[head].step+1;
map[tx][ty]=queue[tail].step;
book[tx][ty]=1;
tail++;
}
}
head++;
}
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
if(map[i][j]==0&&i==a&&j==b)
{
printf("0 ");
continue;
}
if(map[i][j]==0)
{
cout<<-1<<" ";
continue;
}
printf("%-5d",map[i][j]);
}
cout<<endl;
}
return 0;
}