题目描述
有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步
输入输出格式
输入格式:
一行四个数据,棋盘的大小和马的坐标
输出格式:
一个n*m的矩阵,代表马到达某个点最少要走几步(左对齐,宽5格,不能到达则输出-1)
#include<iostream> #include<cstdio> using namespace std; struct wz{ int x,y,z,bnt; }dl[160005]; int ltt[405][405]; int a,b,c,d,i,j,k,l,m,n,tzz; int main() { cin>>a>>b>>c>>d; dl[1].x=c; dl[1].y=d; ltt[c][d]=-1; tzz=1; for(i=1;i<=tzz;i++) { if(dl[i].x+2<=a&&dl[i].y+1<=b) { if(ltt[dl[i].x+2][dl[i].y+1]==0) { tzz++; dl[tzz].bnt=dl[i].bnt+1; ltt[dl[i].x+2][dl[i].y+1]=dl[tzz].bnt; dl[tzz].x=dl[i].x+2; dl[tzz].y=dl[i].y+1; } } if(dl[i].x+1<=a&&dl[i].y+2<=b) { if(ltt[dl[i].x+1][dl[i].y+2]==0) { tzz++; dl[tzz].bnt=dl[i].bnt+1; ltt[dl[i].x+1][dl[i].y+2]=dl[tzz].bnt; dl[tzz].x=dl[i].x+1; dl[tzz].y=dl[i].y+2; } } if(dl[i].x-2>0&&dl[i].y-1>0) { if(ltt[dl[i].x-2][dl[i].y-1]==0) { tzz++; dl[tzz].bnt=dl[i].bnt+1; ltt[dl[i].x-2][dl[i].y-1]=dl[tzz].bnt; dl[tzz].x=dl[i].x-2; dl[tzz].y=dl[i].y-1; } } if(dl[i].x-1>0&&dl[i].y-2>0) { if(ltt[dl[i].x-1][dl[i].y-2]==0) { tzz++; dl[tzz].bnt=dl[i].bnt+1; ltt[dl[i].x-1][dl[i].y-2]=dl[tzz].bnt; dl[tzz].x=dl[i].x-1; dl[tzz].y=dl[i].y-2; } } if(dl[i].x-1>0&&dl[i].y+2<=b) { if(ltt[dl[i].x-1][dl[i].y+2]==0) { tzz++; dl[tzz].bnt=dl[i].bnt+1; ltt[dl[i].x-1][dl[i].y+2]=dl[tzz].bnt; dl[tzz].x=dl[i].x-1; dl[tzz].y=dl[i].y+2; } } if(dl[i].x-2>0&&dl[i].y+1<=b) { if(ltt[dl[i].x-2][dl[i].y+1]==0) { tzz++; dl[tzz].bnt=dl[i].bnt+1; ltt[dl[i].x-2][dl[i].y+1]=dl[tzz].bnt; dl[tzz].x=dl[i].x-2; dl[tzz].y=dl[i].y+1; } } if(dl[i].x+1<=a&&dl[i].y-2>0) { if(ltt[dl[i].x+1][dl[i].y-2]==0) { tzz++; dl[tzz].bnt=dl[i].bnt+1; ltt[dl[i].x+1][dl[i].y-2]=dl[tzz].bnt; dl[tzz].x=dl[i].x+1; dl[tzz].y=dl[i].y-2; } } if(dl[i].x+2<=a&&dl[i].y-1>0) { if(ltt[dl[i].x+2][dl[i].y-1]==0) { tzz++; dl[tzz].bnt=dl[i].bnt+1; ltt[dl[i].x+2][dl[i].y-1]=dl[tzz].bnt; dl[tzz].x=dl[i].x+2; dl[tzz].y=dl[i].y-1; } } } for(m=1;m<=a;m++) { for(n=1;n<=b;n++) { if(m==c&&n==d) { ltt[m][n]=0; printf("%-5d",ltt[m][n]); continue; } if(ltt[m][n]==0) { ltt[m][n]=-1; printf("%-5d",ltt[m][n]); continue; } printf("%-5d",ltt[m][n]); } cout<<endl; } }