悬关,求调简单bfs
查看原帖
悬关,求调简单bfs
746930
NO_OI_NO_LIFE楼主2023/8/15 22:11
#include <bits/stdc++.h>
using namespace std;
struct node{
	int x,y;
}now,top;
int n,m;
int dx[4]={1,-1,2,-2};
int dy[4]={1,-1,2,-2};
int ans[405][405];
bool pd[405][405];
void bfs(int x,int y,int step){
	ans[x][y]=step;
	pd[x][y]=1;
	queue<node> q;
	now.x=x;
	now.y=y;
	
	q.push(now);
	while(!q.empty()){
		top=q.front();
		q.pop();
		for(int i=0;i<4;i++)
			for(int j=0;j<4;j++){
				if(pd[i][j]) continue;
				if(abs(dx[i])==abs(dy[j])) continue;
				int nwx=top.x+dx[i];
				int nwy=top.y+dy[j];
				if(nwx<1||nwx>n||nwy<1||nwy>m) continue;
				
				now.x=nwx;
				now.y=nwy;
				q.push(now);
				ans[nwx][nwy]=ans[top.x][top.y]+1;
				pd[nwx][nwy]=1;
			}
	}
}
int main(){
	//freopen("divisor.in","r",stdin);
	//freopen("divisor.out","w",stdout);
	int x,y;
	cin>>n>>m>>x>>y;
	//cin>>n>>m>>x>>y;
	memset(ans,-1,sizeof ans);
	bfs(x,y,0);
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++)
			cout<<ans[i][j]<<"    ";
		cout<<endl;
	}
	return 0;
}
2023/8/15 22:11
加载中...