poj 3984 迷宫问题 BFS+路径记录

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<stack>
using namespace std;
struct node
{
	int v;
	int fx,fy;
};
node map[10][10];
bool vis[10][10];
int dirx[4]={ 1,-1, 0, 0};
int diry[4]={ 0, 0, 1,-1};
int main()
{
	for(int i=1;i<=5;i++)
	{
		for(int j=1;j<=5;j++)
		{
			scanf("%d",&map[i][j].v);
		}
	}
	queue<node> q;
	map[1][1].fx=1;
	map[1][1].fy=1;
	node start;
	start.fx=1;
	start.fy=1;
	q.push(start);
	vis[1][1]=1;
	while(!q.empty())
	{
		node tmp=q.front();
//		cout << tmp.fx <<','<<tmp.fy<<endl;
		q.pop();
		for(int i=0;i<4;i++)
		{
			node next=tmp;
			next.fx+=dirx[i];
			next.fy+=diry[i];
			if(next.fx<1 || next.fx>5) continue;
			if(next.fy<1 || next.fy>5) continue;
			if(map[next.fx][next.fy].v==1) continue;
			if(vis[next.fx][next.fy]) continue;			
			vis[next.fx][next.fy]=1;
			map[next.fx][next.fy].fx=tmp.fx;
			map[next.fx][next.fy].fy=tmp.fy;
			if(next.fx==5 && next.fy==5) break;
			q.push(next);
		}
	}
	int curx=5,cury=5;
	stack<node> ans; 
	while(!(curx==1 && cury==1))
	{
		node Ans;
		Ans.fx=curx;
		Ans.fy=cury;
		ans.push(Ans);
		int tmpx=map[curx][cury].fx;
		int tmpy=map[curx][cury].fy;
		curx=tmpx;
		cury=tmpy;
	}
	printf("(0, 0)\n");
	while(!ans.empty())
	{
		node Ans=ans.top();
		ans.pop();
		printf("(%d, %d)\n",Ans.fx-1,Ans.fy-1);
	}
//	for(int i=1;i<=5;i++)
//	{
//		for(int j=1;j<=5;j++)
//		{
//			printf("(%d,%d) ",map[i][j].fx,map[i][j].fy);
//		}
//		cout << endl;
//	}
}
这道题 可以不用struct记录路径 可以直接用数字记录信息 因为数字很小 所有完全可以用一个四位数记录,前两位代表行,后两位代表列
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值