2020 蓝桥杯大学 B 组省赛模拟赛(一) J. 程序设计:迷宫 (广度优先搜索)

有一个 n×m 的迷宫,其中 . 表示空地, * 表示障碍物。除此之外,有 q 个单向传送门:如果进入格子 (a_i,b_i),那么会被立即传送到 (c_i,d_i)。保证每个点至多是一个传送门的入口。

如果传送门最终传送到障碍物上,那么将会卡在障碍物上不能移动。

在传送门内部传送的花费是 00,在空地上每次可以往周围四个格子移动,花费是 11。

现在我们想知道从 (1,1) 走到 (x,y) 的最短距离。如果无法到达终点,输出 “No solution”(不含引号)。只要经过终点就算到达,即如果终点上有传送门也没有关系。

输入格式
第一行两个整数 n , m表示地图大小。

接下来 n 行,每行 m 个字符,表示地图。

接下来一行一个整数 q ,表示传送门个数。

接下来 q 行,每行四个整数 a_i,b_i,c_i,d_i。

最后一行两个整数 x,y 表示目的地。

输出格式
一个整数表示最短距离。

数据范围
对于 20% 的数据: 0<n,m≤50,0≤q≤10

对于 50% 的数据: 0<n,m≤200,0≤q≤30

对于 80%80% 的数据: 0<n,m≤500,0≤q≤70

对于 100%100% 的数据: 0<n,m≤1000,0≤q≤100

样例输入复制
3 4
.
.
…*.
2
2 2 2 4
3 1 1 4
3 4
样例输出复制
3

题目链接:https://nanti.jisuanke.com/t/43124
solution:熬了一个通宵的成果!典型的广搜、用map+pair保存传送门。
由于开始把xy保存为了char类型、又找了老半天啊!

#include <bits/stdc++.h>
using namespace std;

char maze[1001][1001];
int dst[1001][1001], n, m, x, y;
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
map< pair<int, int>, pair<int, int> > mp; 

int bfs()
{
	queue<pair<int, int> > que;
	que.push(make_pair(1, 1));
	dst[1][1] = 0;
	while (!que.empty()){
		pair<int, int> temp = que.front();
		que.pop();
		if (maze[temp.first][temp.second] == '*' || dst[temp.first][temp.second] == -1)continue;
		else if (mp.find(temp) != mp.end()){
			dst[mp[temp].first][mp[temp].second] = dst[temp.first][temp.second];
			que.push(mp[temp]);
		}
		else {
			for (int i = 0; i < 4; ++i){
				if (temp.first + dx[i] <= 0 || temp.first + dx[i] > n || temp.second + dy[i] <= 0 || temp.second + dy[i] > m || 
				maze[temp.first + dx[i]][temp.second + dy[i]] == '*' || dst[temp.first + dx[i]][temp.second + dy[i]] != -1)continue;
				dst[temp.first + dx[i]][temp.second + dy[i]] = dst[temp.first][temp.second] + 1;
				que.push(make_pair(temp.first + dx[i], temp.second + dy[i]));
			}
		} 
	}
}

int main()
{
	int q, x1, y1, x2, y2;
	cin >> n >> m;
	for (int i = 1; i <= n; ++i){
		for (int j = 1; j <= m; ++j){
			cin >> maze[i][j];
		}
	}
	cin >> q;
	while (q--){
		cin >> x1 >> y1 >> x2 >> y2;
		mp[make_pair(x1, y1)] = make_pair(x2, y2);		
	}
	cin >> x >> y;
	memset(dst, -1, sizeof dst);
	bfs();
	if (dst[x][y] == -1)cout << "No solution" << endl;
	else cout << dst[x][y] << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值