POJ 6264:走出迷宫

“ Ctrl AC!一起 AC!”

题目:忘题戳这

分析:一道典型的寻路广搜模板题,见博主的往日分析

AC代码:

#include<iostream>
#include<queue>
using namespace std;
struct node {
	int x, y, step;
};//存入队列的位置和步数
char map[210][210];//地图
int visit[210][210];//访问记录
int r1, c1, r2, c2, r, c;
//分别表示起始坐标,终点坐标,最少步数,地图大小
int dx[] = { 0,1,-1,0 };
int dy[] = { 1,0,0,-1 };
//方向数组
int bfs() {
	queue<node> q;//创建队列(每个测试用例都要重新创一个来刷新数据)
	node first;
	first.x = r1; first.y = c1, first.step = 0;
	q.push(first);//初始队头
	while (!q.empty()) {
		node temp = q.front(); q.pop();//摘下队头
		for (int i = 0; i < 4; i++) {//各个方向走一下
			int nowr = temp.x + dx[i];
			int nowc = temp.y + dy[i];
			if (nowr < 0 || nowr >= r || nowc < 0 || visit[nowr][nowc]
				|| nowc >= c || map[nowr][nowc] == '#') continue;//剪枝
			int nowstep = temp.step + 1;
			if (nowr == r2 && nowc == c2) {
				return nowstep;//广搜特点,第一次到达终点即为答案
			}
			node next;
			next.x = nowr; next.y = nowc; next.step = nowstep;
			q.push(next);
			visit[nowr][nowc] = 1;//访问记录
		}
	}
	
}
int main() {
	cin >> r >> c;
	for (int i = 0; i < r; i++) {
		for (int j = 0; j < c; j++) {
			cin >> map[i][j];
			if (map[i][j] == 'S') r1 = i, c1 = j;
			if (map[i][j] == 'T') r2 = i, c2 = j;
		}
	}
	int ans = bfs();
	cout << ans << endl;
	return 0;
}

感谢阅读!!!

“ Ctrl AC!一起 AC!”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ctrl AC

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值