POJ 3984 迷宫【BFS+保存路径】

入门题:http://poj.org/problem?id=3984


#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
#define N 5 
int a[4][2]={{-1,0},{1,0},{0,-1},{0,1}},map[N][N],vist[N][N];
typedef struct
{
	int x,y;
}node;
struct save
{
	int x,y;
}pre[N][N];
queue< node > que;
node s,e;

void ouput( )
{
	node t,tx;
	printf("(%d, %d)\n",s.x,s.y);
	tx.x=s.x,tx.y=s.y;
	while(tx.x != e.x || tx.y != e.y )
	{
		t.x = pre[tx.x][tx.y].x;
		t.y = pre[tx.x][tx.y].y;
		printf("(%d, %d)\n",t.x,t.y);
		tx.x = t.x;
		tx.y = t.y;
	}
}

void bfs()
{
	int i;
	node tmp,cur;
	while( !que.empty() ) que.pop();
	que.push(e);
	while( !que.empty() )
	{
		tmp = que.front();
		que.pop();
		for(i=0;i<4;i++)
		{
			cur.x = tmp.x + a[i][0];
			cur.y = tmp.y + a[i][1];
			if( !vist[ cur.x ][ cur.y ] && map[cur.x][cur.y] == 0 && cur.x>=0 && cur.x<N && cur.y>=0 && cur.y<N )
			{
				vist[ cur.x ][ cur.y ] = 1;
				pre[cur.x][cur.y].x = tmp.x;
				pre[cur.x][cur.y].y = tmp.y;
				que.push(cur);	
				if(cur.x == s.x && cur.y == s.y ) 
				{
					ouput();
					return ;
				}
			}
		}
	}
	return ;
}

int main()
{
	int i,j;
	char xishou;
//	freopen("a.txt","r",stdin);
	for(i=0;i<N;i++)
		for(j=0;j<N;j++)
			scanf("%d%c",&map[i][j],&xishou);
	memset(vist,0,sizeof(vist));
	s.x = s.y = 0 ;
	e.x = e.y = N-1;
	vist[e.x][e.y]=1;
	bfs();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值