蓝桥杯专题 bfs习题详解

1.离开中山路

 

#include<iostream>
#include<cstring>
#include<queue>
#include<algorithm>
#include<string>
using namespace std;
int x1,x2,y1,y2;
int n,n1,m1;
const int N=1010;


typedef pair<int,int> PII;
queue<PII> q;

int dist[N][N];
char g[N][N];

int dx[]={-1,0,1,0};
int dy[]={0,1,0,-1};

int bfs(int x1,int y1)
{
	memset(dist,-1,sizeof dist);
	q.push({x1,y1});//注意格式 
	
	dist[x1][y1]=0;
	while(!q.empty())
	{
		PII t=q.front();
		q.pop();
		for(int i=0;i<4;i++)
		{
			n1=dx[i]+t.first;
			m1=dy[i]+t.second;
			if(n1<1||n1>n||m1<1||m1>n) continue;
			if(g[n1][m1]=='1') continue;
			if(dist[n1][m1]>0) continue;
			
			q.push({n1,m1});
			dist[n1][m1]=dist[t.first][t.second]+1;// ***
			if(n1==x2&&m1==y2)
			{
				return dist[x2][y2];
			}
		}
	}
	return dist[x2][y2];
}


int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=n;j++)
		{
			cin>>g[i][j];
			//scanf("%c",&g[i][j]);
		}
	}
	scanf("%d %d %d %d",&x1,&y1,&x2,&y2);
	int res=bfs(x1,y1);
	cout<<res;
	return 0;
 } 

2.马的遍历

 

//马的遍历
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
/*如何用数组模拟队列:省时间 
对头hh,队尾tt 
 实现队列的插入操作:q[tt++]=x;x是要插入的数字
 实现队列的弹出操作:hh++;
 如何给队列判空:当hh++<=tt 
 int hh=0,tt=0;*/
 typedef pair<int,int> PII;
 
 const int N=410;
 
 int n,m;
 int dist[N][N];
 PII q[N*N];
 
 int dx[]={2,2,1,1,-1,-1,-2,-2};
 int dy[]={-1,1,2,-2,2,-2,1,-1};
 
 void bfs(int x1,int y1)
 {
 	memset(dist,-1,sizeof dist);
 	q[0]={x1,y1};
 	dist[x1][y1]=0;
 	int hh=0,tt=0;
 	
 	while(hh<=tt)
 	{
 		PII t=q[hh++];//t=q.front,why++?
 		//hh++;//pop
 		//t=q[hh++];
 		for(int i=0;i<8;i++)
 		{
 			int a=t.first+dx[i];
 			int b=t.second+dy[i];
 			
 			if(a<1||a>n||b<1||b>m) continue;
 			if(dist[a][b]>=0) continue;
 			
 			dist[a][b]=dist[t.first][t.second]+1;
 			q[++tt]={a,b};//
 			
		 }
	 }
 }
 
int main()
{
	int x1,y1;
	scanf("%d %d %d %d",&n,&m,&x1,&y1);
	bfs(x1,y1);
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
		printf("%-5d",dist[i][j]);//%-5d左补空格,右对齐 
	
		}
		cout<<endl;	
	}
	return 0;
}

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值