[16] 逃离迷宫

题意:假定初始位置和目标位置均为空地,要求过程中转弯数量小于k次,输出yes/no。(如上图)

算法:BFS

问题:一系列小问题,不过有了之前的经验,还是都找出来了。(包括但不限于把加号打成了等号,把应该写在循环里的判断条件写在了while循环运行的条件里,忘记读取qu.front……)但还是第一个错误找的最久,因为之前没犯过……看来犯低级错误也是有一定好处的,毕竟debug这么久总归有些印象。

思路:每次将该方向的位置走尽,转弯数为该循环开始的cur.step(即在原先的上下左右试探的for循环中加一重循环),不然据说……不行(应该是tle)。

代码:ac

#include<bits/stdc++.h>
using namespace std;
int m, n;/*m行n列*/
int t;/*测试组数*/
int k;/*最大转弯次数*/
char Map[110][110];
int sx, sy, ex, ey;/*起点终点坐标*/
struct pos {
	int x, y;
	int step;
};
int vis[110][110];/*是否入过队*/
int dir[4][2] = { {-1,0},{1,0},{0,1},{0,-1} };/*方向*/
void bfs();
int main()
{
	scanf("%d", &t);
	for (int p = 1; p <= t; p++) {
		scanf("%d%d", &m, &n);
		for(int i=1;i<=m;i++)
			for (int j = 1; j <= n; j++) {
				cin >> Map[i][j];
				vis[i][j] = 0;
			}
		scanf("%d%d%d%d%d", &k, &sy, &sx, &ey, &ex);/*题目先给列再给行*/
		bfs();
	}
	return 0;
}
void bfs()
{
	queue<pos>qu;
	pos cur, nex;
	cur.step = -1;
	cur.x = sx, cur.y = sy;
	qu.push(cur);
	vis[sx][sy] = 1;
	while (!qu.empty()) {
		cur = qu.front();
		qu.pop();
		if (cur.x == ex && cur.y == ey && cur.step <= k) {
			printf("yes\n");
			return;
		}
		for (int i = 0; i < 4; i++) {
			nex.x = cur.x + dir[i][0];
			nex.y = cur.y + dir[i][1];
			while (nex.x <= m && nex.x >= 1 && nex.y <= n && nex.y >= 1 &&Map[nex.x][nex.y]=='.') {
				if (vis[nex.x][nex.y] == 0) {
					vis[nex.x][nex.y] = 1;
					nex.step = cur.step + 1;
					qu.push(nex);
				}
				nex.x += dir[i][0];
				nex.y += dir[i][1];
			}
		}
	}
	printf("no\n");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值