1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
#include <bits/stdc++.h> using namespace std; struct node{ int x,y; }; queue<node> q; int ans[402][402]; int n,m,sx,sy; int horse[8][2]={{2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2},{1,-2},{2,-1}}; void bfs(){ while (!q.empty()){ node er=q.front(); int xx=er.x; int yy=er.y; for (int i=0;i<8;i++){ int x=xx+horse[i][0]; int y=yy+horse[i][1]; int sh=ans[xx][yy]; if (x<1 || x>n ||y<1 ||y>m ||ans[x][y]!=-1) continue; ans[x][y]=sh+1; node tmp={x,y}; q.push(tmp); } q.pop(); } } signed main(){ cin>>n>>m>>sx>>sy; memset(ans,-1,sizeof(ans)); node tmp={sx,sy}; q.push(tmp); ans[sx][sy]=0; bfs(); for (int i=1;i<=n;i++){ for (int j=1;j<=m;j++){ printf("%-5d",ans[i][j]); } cout<<endl; } return 0; }
|