Maze(week2 作业A)

Maze

东东有一张地图,想通过地图找到妹纸。地图显示,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)

我的思路:
这道题使用BFS来解决的。对于所给地图,从左上角走到右下角,利用宽度优先搜索,在往下搜索的同时,还要记录当前节点的下一个节点(可以利用map实现)。在找到目标点之后,在利用之前的记录map,完成从起点到终点的路径输出。
我的代码:

#include<iostream>
#include<queue>
#include<map>
#include<stack>
#include<algorithm>
using namespace std;

map< pair<int,int>,pair<int,int> > dis;
int ama[5][5];
int dx[4]={0,0,-1,1};
int dy[4]={-1,1,0,0};
queue< pair<int,int> > Q;
stack< pair<int,int> > A;

void print()
{
	int x=4,y=4;
	pair<int,int> X;
	X.first=x;
	X.second=y;
	A.push(X);
	while(A.top().first!=0||A.top().second!=0)
	{
		pair<int,int> p1;
		pair<int,int> p2;
		p2.first=x;
		p2.second=y;
		p1.first=dis[p2].first;
		p1.second=dis[p2].second;
		A.push(p1);
		int x1=dis[p2].first;
		int y1=dis[p2].second;
		x=x1,y=y1;
	}
	while(!A.empty())
	{
		x=A.top().first;
		y=A.top().second;
		A.pop();
		cout<<"("<<x<<", "<<y<<")"<<endl;
	}
}

void bfs()
{
	pair<int,int> p1;
	p1.first=0;
	p1.second=0;
	Q.push(p1);
	while(!Q.empty())
	{	
		int x=Q.front().first,y=Q.front().second;
		Q.pop();
		if(ama[x][y]) break;
		ama[x][y]=1;
		for(int i=0;i<4;i++)
		{
			int x1=x+dx[i],y1=y+dy[i];
			if(x1>=0&&x1<=4&&y1>=0&&y1<=4&&!ama[x1][y1])
			{
	p1.first=x1;
	p1.second=y1;
				dis[p1].first=x;
				dis[p1].second=y;
				if(x1==4&&y1==4) {
					print();
					return;
				}
	p1.first=x1;
	p1.second=y1;
				Q.push(p1);
			}
			
		}
	}
}

int main()
{
	for(int i=0;i<5;i++)
	  for(int k=0;k<5;k++)
	  	cin>>ama[i][k];
	bfs();
	return 0;
 } 
发布了26 篇原创文章 · 获赞 0 · 访问量 456

猜你喜欢

转载自blog.csdn.net/qq_43738677/article/details/104675071