洛谷P1443 马的遍历(BFS)

洛谷P1443 马的遍历


蒟蒻第一篇题解&博客

一道基本的广搜,也是我第一次完整地自己写出来的广搜,菜死了。。。

大概思路就是从最初的位置开始,遍历八个方向,符合条件的放到队列里,然后出队一个点执行上述操作,直到队列为空。还是挺好写的,个人感觉比深搜好写,也好想。

代码不是很简洁,但是我自己好理解

上代码:

#include <iostream>
#include <stdio.h>
#include <queue>
using namespace std;
struct node{
    
    	//点 
	int x;
	int y;
};
int a[401][401];
int m,n,x0,y0;
int dir[8][2]={
    
    {
    
    2,-1},{
    
    2,1},{
    
    1,2},{
    
    -1,2},{
    
    -2,1},{
    
    -2,-1},{
    
    -1,-2},{
    
    1,-2}};//马能到的八个方向 
bool check(int p,int q)//检查是否符合要求 
{
    
    
	if(p>=0&&p<=m-1&&q>=0&&q<=n-1&&a[p][q]==-1)	return true;
	else return false;
}
void bfs(int x1,int y1) 
{
    
    
	queue<node>q;
	node next,start;
	int nx,ny,k;
	start.x=x1;
	start.y=y1;
	q.push(start);//最初的点入队 
	while(!q.empty()){
    
    
		next=q.front();
		q.pop();
		for(int i=0;i<8;i++){
    
    //遍历八个方向 
			nx=next.x;
			ny=next.y;
			k=a[nx][ny];
			nx+=dir[i][0];
			ny+=dir[i][1];
			if(check(nx,ny)){
    
    //符合条件就入队 
				a[nx][ny]=k+1;
				start.x=nx;
				start.y=ny;
				q.push(start);
			}
		}
	}
}
void print()
{
    
    
	for(int i=0;i<m;i++){
    
    
		for(int j=0;j<n;j++) printf("%-5d",a[i][j]);//注意这个输出格式 
		cout<<endl;
	}
}
int main()
{
    
    
	cin>>m>>n>>x0>>y0;
	for(int i=0;i<m;i++){
    
    
		for(int j=0;j<n;j++) a[i][j]=-1;
	}
	x0-=1;y0-=1;
	a[x0][y0]=0;
	bfs(x0,y0);
	print();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45743427/article/details/108903868