算法-程序设计课week2---作业A - Maze POJ - 3984

A - Maze POJ - 3984

东东有一张地图,想通过地图找到妹纸。地图显示,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开始,且以左上角为原点。另外注意,输出中分隔坐标的逗号后面应当有一个空格。

思路有收获
做过多遍的走迷宫问题,通过广度优先搜索来解决,注意加入新点的条件包括 边界 是否已经访问 是否有墙。

如果手动给边界加一层墙,可以简化判断逻辑。

#include<cstdio>
#include<queue>
using namespace std;

typedef struct point {
	int x,y;
	point(int a,int b):x(a),y(b) {
	}
	point():x(0),y(0) {
	}
	inline bool operator == (const point& b) {
		return x==b.x && y==b.y;
	}
} point;

int map[6][6];
int visited[6][6]; //表示访问过与否
point pre[6][6];//表示来源节点,用于溯源路径


inline bool over(point next) {
	return (next.x>=0&&next.x<=4)&&(next.y>=0&&next.y<=4);
}
void bfs(point start, point target) {
	queue<point> q;//待访问节点 

	pre[start.x][start.y]=start;
	q.push(start);
	while(!q.empty()) {
		//获取待访问节点 
		point cur=q.front();q.pop();
		//检查退出条件 
		if(cur==target)break;
		//节点已访问 
		visited[cur.x][cur.y]=1;
		
		
		//添加新节点
		point next;

		next.x=cur.x+1;
		next.y=cur.y+0;
		if(
		    over(next)&&//检测越界
		    map[next.x][next.y]==0&&//检测障碍
		    visited[next.x][next.y]==0//检测是否走过
		) {
			q.push(next);
			pre[next.x][next.y]=cur;//记录其来源
		}

		next.x=cur.x+0;
		next.y=cur.y+1;
		if(
		    over(next)&&//检测越界
		    map[next.x][next.y]==0&&//检测障碍
		    visited[next.x][next.y]==0//检测是否走过
		) {
			q.push(next);
			pre[next.x][next.y]=cur;//记录其来源
		}

		next.x=cur.x-1;
		next.y=cur.y+0;
		if(
		    over(next)&&//检测越界
		    map[next.x][next.y]==0&&//检测障碍
		    visited[next.x][next.y]==0//检测是否走过
		) {
			q.push(next);
			pre[next.x][next.y]=cur;//记录其来源
		}

		next.x=cur.x+0;
		next.y=cur.y-1;
		if(
		    over(next)&&//检测越界
		    map[next.x][next.y]==0&&//检测障碍
		    visited[next.x][next.y]==0//检测是否走过
		) {
			q.push(next);
			pre[next.x][next.y]=cur;//记录其来源
		}
	}
}

int main() {
	for(int i=0; i<5; i++)
		for(int j=0; j<5; j++)
			scanf("%d",&map[i][j]);


	bfs(point(4,4),point(0,0));
	printf("(0, 0)\n");
	point cur(0,0);
	while(!(cur==point(4,4))) {
		cur=pre[cur.x][cur.y];
		printf("(%d, %d)\n",cur.x,cur.y);
	}
	return 0;
}



发布了166 篇原创文章 · 获赞 21 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/lgfx21/article/details/104739259
今日推荐