Week2 A - 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)

Hint
  坐标(x, y)表示第x行第y列,行、列的编号从0开始,且以左上角为原点。

另外注意,输出中分隔坐标的逗号后面应当有一个空格。

解题关键 BFS

bool bfs(Point &pb,Point &pe){
	queue<Point> qu;//建队列
	int r[][2]={{0,-1},{0,1},{1,0},{-1,0}};//四种方向
	parent[pb.x][pb.y]=pb;//查找起点
	qu.push(pb);//入队
	while(!qu.empty()){
		Point temp=qu.front();
		qu.pop();//出队
		v[temp.x][temp.y]=1;//这个点标记为已经过
		if(temp.x==pe.x&&temp.y==pe.y)return true;
		for(int i=0;i<4;++i){//四个方向
			Point temp2(temp.x+r[i][0],temp.y+r[i][1]);
			if(b[temp2.x][temp2.y]==0&&v[temp2.x][temp2.y]==0){
				qu.push(temp2);
				parent[temp2.x][temp2.y]=temp;
			}
		}
	} 
	 return false;
}

struct point
Point parent[a1][a2];-> x=b1,y=b2
parent 记录这个点的父节点
输出时可用 parent[a1][a2].x parent[a1][a2].y 作为下个输出的[x][y]

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int b[7][7];
int v[7][7];//用二维数组记录迷宫
struct Point
{
    int x;
    int y;
    Point(){};
    Point(int _x,int _y){x=_x;y=_y;};
};
Point parent[7][7];

bool bfs(Point &pb,Point &pe){
	queue<Point> qu;
	int r[][2]={{0,-1},{0,1},{1,0},{-1,0}};
	parent[pb.x][pb.y]=pb;
	qu.push(pb);
	while(!qu.empty()){
		Point temp=qu.front();
		qu.pop();
		v[temp.x][temp.y]=1;
		if(temp.x==pe.x&&temp.y==pe.y)return true;
		for(int i=0;i<4;++i){
			Point temp2(temp.x+r[i][0],temp.y+r[i][1]);
			if(b[temp2.x][temp2.y]==0&&v[temp2.x][temp2.y]==0){
				qu.push(temp2);
				parent[temp2.x][temp2.y]=temp;
			}
		}
		
	} 
	 return false;
}




int main(){
	for(int i=0;i<7;i++){
		b[0][i]=1;
	}
	for(int i=0;i<7;i++){
		b[6][i]=1;
	}
	for(int i=0;i<7;i++){
		b[i][0]=1;
	}
	for(int i=0;i<7;i++){
		b[6][i]=1;
	}
	memset(v,0,sizeof(v));
	for(int i=1;i<=5;i++){
		for(int y=1;y<=5;y++){
			cin>>b[i][y];
		}
	}
	
	Point begin(1,1),end(5,5);
        if(bfs(end,begin))
        {
            Point a(1,1);
            cout<<"(0, 0)"<<endl;
            while(a.x!=5||a.y!=5)
            {
                a=parent[a.x][a.y];
                cout<<'('<<a.x-1<<", "<<a.y-1<<')'<<endl;

            }
        }
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值