蒟蒻bfs求助
查看原帖
蒟蒻bfs求助
484312
Babatos楼主2021/7/27 08:57
#include<bits/stdc++.h>
using namespace std;
int n,m,x,y,a[401][401],step[401];
int ax[410],ay[410];
const int dx[8]={-1,-2,-2,-1,1,2,2,1};
const int dy[8]={2,1,-1,-2,2,1,-1,-2};
int bfs(int p,int q,int head,int last,int d,int e){
	int b[410][410]={};
	ax[1]=p;
	ay[1]=q;
	step[1]=0;
	while(head<last){
		head++;
		for(int z=0;z<8;z++){
			int nx=ax[head]+dx[z];
			int ny=ay[head]+dy[z];
			if(nx==d&&ny==e){
				return step[last];
			}
			else if(nx>=1&&nx<=n&&ny>=1&&ny<=m&&b[nx][ny]==0){
				b[nx][ny]=1;
				last++;
				ax[last]=nx;
				ay[last]=ny;
				step[last]=step[head]+1;
			}			
		}
	}
//	for(int i=1;i<=last;i++){
//		cout<<xx[i]<<" "<<yy[i]<<endl;
//	}
	return -1;
}
int main(){
	cin>>n>>m;
	cin>>x>>y;
	a[x][y]=0;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			if(i!=x||j!=y){
//				a[3][3]=bfs(x,y,0,1,3,3);
//				cout<<a[3][3];
				a[i][j]=bfs(x,y,0,1,i,j);
			}
		}
	}
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			cout<<a[i][j]<<"    ";
		}
		cout<<endl;
	}
	return 0;
}```
2021/7/27 08:57
加载中...