n行m列

P1443 马的遍历

``` #include<bits/stdc++.h> using namespace std; queue<int> q,p; int n,m,x,y; int f[410][410],step[410][410]; int dx[8]={-1,1,2,2,1,-1,-2,-2}; int dy[8]={-2,-2,-1,1,2,2,1,-1}; void bfs(int x,int y) { q.push(x); p.push(y); f[x][y]=1; step[x][y]=0; while(!q.empty()) { int nowx=q.front(); int nowy=p.front(); q.pop(); p.pop(); for(int i=0;i<8;i++) { int tx=nowx+dx[i]; int ty=nowy+dy[i]; if(tx<1|| ty>m ||tx>n ||ty<1||f[tx][ty]==1) { continue; } f[tx][ty]=1; step[tx][ty]=step[nowx][nowy]+1; q.push(tx); p.push(ty); } } } int main(){ cin>>n>>m>>x>>y; for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { step[i][j]=-1; } } bfs(x,y); for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { printf("%-5d",step[i][j]); } cout<<endl; } return 0; } ``` **这样做**
by wangzien @ 2023-11-09 22:23:17


|