题解
2026-08-07 20:26:21
发布于:浙江
11阅读
0回复
0点赞
这题有点难
注意:这里输出要用
printf("%-5d",num);
输出
#include <bits/stdc++.h>
using namespace std;
const int N = 405;
struct node
{
int x,y;
};
int n,m,x,y,step[N][N],ans,dx[8] = {2,2,1,-1,-2,-2,1,-1},dy[8] = {1,-1,2,2,1,-1,-2,-2};
int mp[N][N];
queue <node> q;
bool vis[N][N];
bool check(int x,int y)
{
if(x < 1 || x > n || y < 1 || y > m)
{
return 0;
}
if(vis[x][y]) return 0;
return 1;
}
void bfs()
{
while(!q.empty())
{
auto it = q.front();
q.pop();
for(int i = 0;i < 8;i ++)
{
int nx = it.x + dx[i];
int ny = it.y + dy[i];
if(check(nx,ny))
{
q.push({nx,ny});
vis[nx][ny] = 1;
step[nx][ny] = step[it.x][it.y] + 1;
}
}
}
}
int main()
{
cin >> n >> m >> x >> y;
q.push({x,y});
for(int i = 1;i <= n;i ++)
{
for(int j = 1;j <= m;j ++)
{
bfs();
}
}
step[x][y] = 0;
for(int i = 1;i <= n;i ++)
{
for(int j = 1;j <= m;j ++)
{
if(step[i][j] != 0) printf("%-5d",step[i][j]);
else if(i == x && j == y) printf("%-5d",0);
else printf("%-5d",-1);
}
cout << "\n";
}
return 0;
}
有用请点个赞。
这里空空如也






有帮助,赞一个