poj 3984 迷宫问题 (bfs入门)

迷宫问题

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 7688 Accepted: 4502

Description

定义一个二维数组: 

int maze[5][5] = {

	0, 1, 0, 0, 0,

	0, 1, 0, 1, 0,

	0, 0, 0, 0, 0,

	0, 1, 1, 1, 0,

	0, 0, 0, 1, 0,

};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

Input

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

Output

左上角到右下角的最短路径,格式如样例所示。

Sample Input

0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

Sample Output

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

#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
#include <stack>
using namespace std;


int map[5][5];
struct Node{
	int fx,fy;
}node[5][5];
queue<pair<int,int> > q; 
stack<pair<int,int> > ha;
int main ()
{
	int x,y;
	//freopen ("in.txt","r",stdin);
	for (int i=0;i<5;i++)
		for (int j=0;j<5;j++){
			scanf("%d",&map[i][j]);
	//		printf("%d ",map[i][j]);
		}
	q.push(make_pair(0,0));
	while (q.back()!=make_pair(4,4))
	{
		x=q.front().first;
		y=q.front().second;
		if(x>0) {
			if(map[x-1][y]==0) {
				q.push(make_pair(x-1,y));
				node[x-1][y].fx=x;
				node[x-1][y].fy=y;
				map[x-1][y]=1;
			}
		}
		if(y>0) {
			if(map[x][y-1]==0) {
				q.push(make_pair(x,y-1));
				node[x][y-1].fx=x;
				node[x][y-1].fy=y;
				map[x][y-1]=1;
			}
		}
		if(x<4) {
			if(map[x+1][y]==0) {
				q.push(make_pair(x+1,y));
				node[x+1][y].fx=x;
				node[x+1][y].fy=y;
				map[x+1][y]=1;

				//cout<<x<<" "<<y<<endl;
			}
			//if(x+y==7) break;
		}
		if(y<4) {
			if(map[x][y+1]==0) {
				q.push(make_pair(x,y+1));
				node[x][y+1].fx=x;
				node[x][y+1].fy=y;
				map[x][y+1]=1;
			}
			//if(x+y==7) break;
		}
		q.pop();
		//cout<<node[3][4].fx<<" "<<node[3][4].fy<<endl;
	}
	//int x,y;

	//cout<<node[3][4].fx<<" "<<node[3][4].fy<<endl;
	x=4,y=4;
	ha.push(make_pair(4,4));
	while (x!=0||y!=0)
	{
		int xa=x;
		x=node[xa][y].fx;
		y=node[xa][y].fy;

		//cout<<x<<y<<endl;
		ha.push(make_pair(x,y));
	}
	while (ha.size())
	{
		printf("(%d, %d)\n",ha.top().first,ha.top().second);
		ha.pop();
	}
	return 0;
	
	
}

    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/alpc_paul/article/details/38116841
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞