SDU_week2_A - Maze(BFS迷宫问题)

题目描述

东东有一张地图,想通过地图找到妹纸。地图显示,0表示可以走,1表示不可以走,左上角是入口,右下角是妹纸,这两个位置保证为0。既然已经知道了地图,那么东东找到妹纸就不难了,请你编一个程序,写出东东找到妹纸的最短路线。

Input
  输入是一个5 × 5的二维数组,仅由0、1两数字组成,表示法阵地图。

Output
  输出若干行,表示从左上角到右下角的最短路径依次经过的坐标,格式如样例所示。数据保证有唯一解。

Sample Input
0 1 0 0 0
0 1 0 1 0
0 1 0 1 0
0 0 0 1 0
0 1 0 1 0

Sample Output
(0, 0)
(1, 0)
(2, 0)
(3, 0)
(3, 1)
(3, 2)
(2, 2)
(1, 2)
(0, 2)
(0, 3)
(0, 4)
(1, 4)
(2, 4)
(3, 4)
(4, 4)

Hint
坐标(x, y)表示第x行第y列,行、列的编号从0开始,且以左上角为原点。
另外注意,输出中分隔坐标的逗号后面应当有一个空格。

分析

本题是典型的BFS迷宫问题(甚至还做了简化),有两种思路框架:

  1. 定义二维的map坐标,map的数据类型用结构体表示,用于记录坐标位置、是否走过、是第几步。本人采用了这种方法。
  2. 定义很多二维数组,称之为地图数组、标记数组、路径数组etc。

然后利用STL中的queue进行BFS,再利用stack存入输出结点(目的是防递归)。经过测试,STL均采用深拷贝,可以随意赋值使用,不必担心引用问题。

代码

#define _CRT_SECURE_NO_WARNINGS
//#include <bits/stdc++.h>
#include <iostream>
#include<stack>
#include<queue>
#include<algorithm>

using namespace std;

#define _ ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)

struct point
{
	int x ;
	int y ;
	int label ;//是否到达过
	int step ;//第几步

	//point(const point& p)
	//{
	//	this->x = p.x;
	//	this->y = p.y;
	//	this->label = p.label;
	//	this->step = p.step;
	//}
};

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


int main()
{
	point map[5][5];
	memset(map, 0, sizeof(map));


	for (int i = 0; i < 5; i++)
	{
		for (int j = 0; j < 5; j++) {
			map[i][j].x = i;
			map[i][j].y = j;
			cin >> map[i][j].label;
		}
	}

	int dis = 0;//路径长度
	queue<point> q;
	q.push(map[0][0]);
	while (!q.empty())
	{
		point current = q.front();
		q.pop();
		if (current.x == 4 && current.y == 4)
		{//到达终点
			dis = current.step;
			break;
		}

		for (int i = 0; i < 4; i++) {
			int x_ = current.x + dx[i];
			int y_ = current.y + dy[i];
			if (map[x_][y_].label == 0 && x_ >= 0 && x_ <= 4 && y_ >= 0 && y_ <= 4) {
				map[x_][y_].label = 1;
				map[x_][y_].step = current.step + 1;
				q.push(map[x_][y_]);
			}
		}
	}

	stack<point> qout;//从后向前找路,dis依次减一,直到为0
	qout.push(map[4][4]);
	dis--;
	while (dis > 0) {
		point current = qout.top();
		for (int i = 0; i < 4; i++) {
			int x_ = current.x + dx[i];
			int y_ = current.y + dy[i];
			if (x_ >= 0 && x_ <= 4 && y_ >= 0 && y_ <= 4 && map[x_][y_].step == dis) {
				qout.push(map[x_][y_]);
				dis--;
				break;//找到一个就break掉,虽然本题保证唯一解,用不上
			}
		}
	}

	cout << "(" << 0 << ", " << 0 << ")" << endl;//输出起点,因为是从dis=1开始的
	while (!qout.empty()) {
		cout << "(" << qout.top().x << ", " << qout.top().y << ")" << endl;
		qout.pop();
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值