洛谷P1443马的遍历

题目点这里
在这里插入图片描述很简单的一道bfs,唯一要注意的点便是输出的格式。开始将起点赋值0,其他全部初始化为-1即可。

代码如下

#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<queue>
using namespace std;
int sx,sy,step[410][410],n,m,fx[8]={1,2,1,2,-1,-2,-1,-2};
int fy[8]={2,1,-2,-1,-2,-1,2,1};
int pan(int x){
	if(x>=10000) return 5;
	if(x>=1000) return 4;
	if(x>=100) return 3;
	if(x>=10) return 2;
	if(x>=0) return 1;
	return 2;
}
int main(){
	memset(step,-1,sizeof(step));
	cin>>n>>m>>sx>>sy;
	step[sx][sy]=0;
	queue<int> q[2];
	q[0].push(sx);
	q[1].push(sy);
	while(!q[0].empty()){
		  for(int i=0;i<=7;i++){
		  	  int x=q[0].front()+fx[i],y=q[1].front()+fy[i];
		  	  if(x>=1&&x<=n&&y>=1&&y<=m&&step[x][y]==-1){
		  	  	   step[x][y]=step[q[0].front()][q[1].front()]+1;
		  	  	   q[0].push(x);
		  	  	   q[1].push(y);
				}
		  }
		q[0].pop();
		q[1].pop();
	}
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			cout<<step[i][j];
			for(int k=1;k<=5-pan(step[i][j]);k++) cout<<" ";
		}
		cout<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_32017563/article/details/87717524