2020 计蒜客蓝桥杯B 组模拟赛(一)——迷宫

[2020 计蒜客蓝桥杯B 组模拟赛(一)——迷宫]

用bfs队列实现

#include <bits/stdc++.h>
#define maxn 1005
#define maxm 1005
#define maxq 105
using namespace std;
typedef pair<int,int> pii;

char mmap[maxn][maxm];//迷宫地图 
int dir[4][2]={{-1,0},{0,1},{1,0},{0,-1}};//四个方向 
int a[maxq],b[maxq],c[maxq],d[maxq];
int n,m,q,x,y;
pii point;//记录传送到的点 
queue<pii> Q; 
bool inq[maxn][maxm];//判断是否入队,防止重复入队 
int dis[maxn][maxm];//记录每个点离起点的最小距离 

//判断是否位传送门
//并记录传送到哪个点 
bool chuansong(int x,int y){
	for(int i=0;i<q;i++){
		if(x==a[i] && y==b[i]){
			point.first=c[i];
			point.second=d[i];
			return true;
		}
	}
	return false;
}
//判断是否在地图内 
bool inmap(int x,int y){
	if(x>=1 && x<=n && y>=1 && y<=m) return true;
	else return false;
}
void init(){
	memset(dis,127,sizeof(dis));//将初始距离设置为无穷大 
	while(!Q.empty()){
		Q.pop();
	}
}

void bfs(int sx,int sy){
	Q.push(make_pair(sx,sy));
	inq[sx][sy]=true;
	dis[sx][sy]=0;
	while(!Q.empty()){
		sx=Q.front().first;
		sy=Q.front().second;
		Q.pop();
		inq[sx][sy]=false;
		if(chuansong(sx,sy)){
			if(mmap[point.first][point.second]=='.' && dis[sx][sy]<dis[point.first][point.second]){
				int tx=point.first;
				int ty=point.second;
				dis[tx][ty]=dis[sx][sy]; 
				mmap[tx][ty]='#';
				if(!inq[tx][ty]){
					Q.push(make_pair(tx,ty));
					inq[tx][ty]=true;
				}
			}
		}
		else{
			for(int i=0;i<4;i++){
				int tx=sx+dir[i][0];
				int ty=sy+dir[i][1];
				if(mmap[tx][ty]=='.' && inmap(tx,ty) && dis[sx][sy]+1< dis[tx][ty]){
					dis[tx][ty]=dis[sx][sy]+1;			
					mmap[tx][ty]='#';
					if(!inq[tx][ty]){
						Q.push(make_pair(tx,ty));
						inq[tx][ty]=true;
					}
				}
			}	
		}
	}
} 

int main(){
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			cin>>mmap[i][j];
		}
	}
	cin>>q;
	for(int i=0;i<q;i++){
		cin>>a[i]>>b[i]>>c[i]>>d[i];
	} 
	cin>>x>>y;
	init();
	bfs(1,1);
	if(dis[x][y]!=0x7f7f7f7f) cout<<dis[x][y]<<endl;
	else cout<<"No solution"<<endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值