迷宫问题-广度优先搜索

http://blog.csdn.net/u014713819/article/details/26723313

理论看这个

迷宫问题:

#include<iostream>
#include <deque>
#include <stack>
#include <vector>
using namespace  std;
const int di[4] = {0,1,0,-1},
			dj[4] = {1,0,-1,0};
//四组方向
/*unsigned 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};

unsigned flag[5][5] = {0};*/ //访问标准,记录路径
typedef struct 
{
	int i;
	int j;
	int dis;
}node; 

deque<node> dnode;
//根据flag数组反向查找路径
stack<node> getpath(vector<vector<int> >& f,int x,int y,int d,int pos2x,int pos2y)
{
	node first,last;
	stack<node> ret;
	first.i = pos2x;
	first.j = pos2y;
	first.dis = d;
	ret.push(first);
	while(first.dis != 1)
	{
		for(int i=0;i<4;++i)
		{
			if(first.i+di[i]>=0 &&first.i+di[i]<x 
				&& first.j+dj[i]>=0 &&first.j+dj[i]<y
				&& f[first.i+di[i]][first.j+dj[i]]==(first.dis-1))
			{
				last.i = first.i+di[i];
				last.j = first.j+dj[i];		
				last.dis = first.dis-1;
				ret.push(last);
				first = last;
			}
		}		
	}
	return ret;
}

int main(void)
{
	//维度
	int x,y;
	cin>>x>>y;
	vector<vector<int> > maze;
	vector<int> mazetemp;
	int temp;
	//输入maze
	for (int i=0;i<x;++i)
	{
		for(int j=0;j<y;++j)
		{
			cin>>temp;
			mazetemp.push_back(temp);
		}
		maze.push_back(mazetemp);
		mazetemp.clear();
	}
	//访问记录
	vector<vector<int> > flag;
	for (int i=0;i<x;++i)
	{
		for(int j=0;j<y;++j)
		{
			mazetemp.push_back(0);
		}
		flag.push_back(mazetemp);
		mazetemp.clear();
	}
	//起始和终止位置
	int pos1x,pos1y,pos2x,pos2y;
	cin>>pos1x>>pos1y>>pos2x>>pos2y;

	node first,last;
	first.i = pos1x;
	first.j = pos1y;
	first.dis = 0;
	dnode.push_back(first);
	while(!dnode.empty())  //bfs
	{
		first = dnode.front();
		dnode.pop_front();
		flag[pos1x][pos1y]=1;
		for(int i=0;i<4;++i)
		{
			if(first.i+di[i]>=0 &&first.i+di[i]<x 
				&& first.j+dj[i]>=0 &&first.j+dj[i]<y
				&& maze[first.i+di[i]][first.j+dj[i]]==0
				&& flag[first.i+di[i]][first.j+dj[i]]==0)
			{
				last.i = first.i+di[i];
				last.j = first.j+dj[i];		
				last.dis = first.dis+1;
				flag[last.i][last.j] = last.dis+1;
				dnode.push_back(last);
				if(last.i==pos2x &&last.j==pos2y)
				{				
					cout<<"have path"<<endl;
					stack<node> ret = getpath(flag,x,y,last.dis+1,pos2x,pos2y);
					while(!ret.empty())
					{
						cout<<'('<<ret.top().i<<','<<ret.top().j<<')'<<"->";
						ret.pop();
					}
					return 0;
				}
			}
		}		
	}
	printf("No path.\n");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值