longyitongxue @ 2024-12-07 21:14:41
费劲心思做出来一个
#include<iostream>
#include<string.h>
#include<queue>
#include<stdio.h>
using namespace std;
struct node
{
int x,y,cnt;
};
int n,m;
bool vis[405][405];
int dx[8]= {2,-2,2,-2,1,-1,1,-1};
int dy[8]= {1,1,-1,-1,2,2,-2,-2};
int bfs(int sx,int sy,int ex,int ey)
{
queue<node> q;
q.push({sx,sy,0});
while(q.size()){
node t=q.front();
q.pop();
for(int i=0;i<8;i++){
int nx=t.x+dx[i];
int ny=t.y+dy[i];
if(nx==ex&&ny==ey){
return t.cnt+1;
}
if(1<=nx&&nx<=n&&1<=ny&&ny<=m&&!vis[nx][ny]){
vis[nx][ny]=1;
q.push({nx,ny,t.cnt+1});
}
}
}
return -1;
}
int main()
{
int sx,sy;
cin>>n>>m>>sx>>sy;
for(int i=1; i<=n; i++)
{
for(int j=1; j<=m; j++)
{
memset(vis,false,sizeof(vis));
if(i==sx&&j==sy){
printf("0 ");
continue;
}
vis[sx][sy]=1;
printf("%-5d",bfs(sx,sy,i,j));
}
putchar('\n');
}
return 0;
}
感谢您提供的指导
by masonxiong @ 2024-12-07 21:23:49
@longyitongxue
直接从起点开始搜,记录每个点的 dis
就行。
by longyitongxue @ 2024-12-08 12:56:39
互关,thanks@masonxiong