社区讨论

bfs 0求调

P1443马的遍历参与者 2已保存回复 2

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
2 条
当前快照
1 份
快照标识符
@mhjt0adt
此快照首次捕获于
2025/11/04 08:01
4 个月前
此快照最后确认于
2025/11/04 08:01
4 个月前
查看原帖
CPP
#include <bits/stdc++.h>
using namespace std;
int n,m,x,y;
int vis[405][405],ans[405][405];
struct node
{
	int x,y,step;
};
void bfs(int x,int y)
{
	int nxt[8][2]={{1,-2},{1,2},{-1,2},{-1,-2},{-2,1},{2,1},{2,-1},{-2,-1}};
	queue<node> q;
	vis[x][y]=1;
	q.push((node){x,y,0});
	while(!q.empty())
	{
		node pre=q.front();
		ans[pre.x][pre.y]=pre.step;
		q.pop();
		for(int i=0;i<=7;i++)
		{
			int nx=pre.x+nxt[i][0];
			int ny=pre.y+nxt[i][1];
			if(nx>=1&&nx<=n&&ny>=1&&ny>=m&&vis[nx][ny]==0)
			{
				vis[nx][ny]=1;
				q.push((node){nx,ny,pre.step+1});
			}	
		}	
	}	
}	
int main() {
	cin>>n>>m>>x>>y;
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			ans[i][j]=-1;
		}
	}
	bfs(x,y);
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			ans[i][j]=-1;
		}
	}
	bfs(x,y);
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			cout<<ans[i][j]<<" ";
		}
		cout<<endl;
	}
	return 0;
}
bfs 0分 求调

回复

2 条回复,欢迎继续交流。

正在加载回复...