题解 广搜记录路径 POJ 3984

题意: 定义一个二维数组: 
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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

做法:1 广搜寻找最短路径;

 2 建立数组用于记录路径 从结果开始查找父亲节点;

附:坐标压缩法
顾名思义,就是将本来是用两个数来表示的坐标(x, y),用一个数来表示。
为什么?简便呗!
第i行第j列的格子编号为i*m+j
反之,编号为u的节点,其行号和列号分别为u / m; u % m;

代码:
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
int i,j,m,re;
int num[5][5];
int loc[5][5];
queue<int>que;
stack <int > sta;
bool inbound(int x)
{
	if (x >=0)
		if (x < 5)
			return true;
		else
			return false;
	else
		return false;
}
void bfs(int x,int y)
{
    m=que.size();
    for(i=0;i<m;i++)
    {
    if(inbound(x-1)&&inbound(y)&&num[x-1][y]==0&&loc[x][y]==0)
        {que.push(5*(x-1)+y);num[x-1][y]=num[x][y]+1;}
    if(inbound(x)&&inbound(y-1)&&num[x][y-1]==0&&loc[x][y]==0)
        {que.push(5*x+y-1);num[x][y-1]=num[x][y]+1;}
    if(inbound(x)&&inbound(y+1)&&num[x][y+1]==0&&loc[x][y]==0)
        {que.push(5*x+y+1);num[x][y+1]=num[x][y]+1;}
    if(inbound(x+1)&&inbound(y)&&num[x+1][y]==0&&loc[x][y]==0)
        {que.push(5*(x+1)+y);num[x+1][y]=num[x][y]+1;}
    }
    que.pop();
}
void print(int x, int y)
{
    if(inbound(x-1)&&inbound(y)&&num[x-1][y]==num[x][y]-1&&loc[x-1][y]==0)
        {re--;sta.push(5*(x-1)+y);print(x-1,y);}
    else if(inbound(x)&&inbound(y-1)&&num[x][y-1]==num[x][y]-1&&loc[x][y-1]==0)
        {re--;sta.push(5*x+y-1);print( x,  y-1);}
    else if(inbound(x)&&inbound(y+1)&&num[x][y+1]==num[x][y]-1&&loc[x][y+1]==0)
         {re--;sta.push(5*x+y+1);print(x, y+1);}
    else if(inbound(x+1)&&inbound(y)&&num[x+1][y]==num[x][y]-1&&loc[x+1][y]==0)
       {re--;sta.push(5*(x+1)+y);print(x+1,  y);}
}
int main()
{
    for(i=0;i<5;i++)
        for(j=0;j<5;j++)
        num[i][j]=0,cin>>loc[i][j];
        que.push(0);
    while(num[4][4]==0)bfs(que.front()/5,que.front()%5);
    re=num[4][4];
    /*cout<<num[4][4]<<endl;*/
    print(4,4);
    cout<<"(0, 0)"<<endl;
    while(sta.size()!=0)
    {
        cout<<"("<<sta.top()/5<<", "<<sta.top()%5<<")"<<endl;
        sta.pop();
    }
    cout<<"(4, 4)"<<endl;
    return 0;
}




转载于:https://www.cnblogs.com/ghh1995/p/4349039.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值