POJ - 3984 迷宫问题

15 篇文章 0 订阅

更好的阅读体验

【想法】题目简单,长宽都固定了下来,直接深搜就行。就是记录路径有点障碍,稍微一想就行,还是那句话:一个人可能有多个儿子,但是一定只有一个爸爸,所以每次搜索的时候直接记录当前节点的爸爸是谁就行,然后由最后依次向前统计出路径,压到栈中,反序输出就是答案了。因为起始点和终止点都固定了下来,所以可以用特征值直接扫出答案。

【代码】

#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <stack>
using namespace std;
int mat[10][10];
int pre[10][10];
struct P
{
    int x,y;
    P(int X,int Y):x(X),y(Y){}
};
queue<int>lu;
int changex[4]={0,0,1,-1};
int changey[4]={1,-1,0,0};
int main()
{
    //freopen("in.txt","r",stdin);
    for(int i=0;i<5;i++)
        for(int j=0;j<5;j++)
        {
            scanf("%d",&mat[i][j]);
            pre[i][j]=i*1000+j;
        }
    lu.push(0);
    int x,y,cx,cy;
    while(!lu.empty())
    {
        x=lu.front()/1000;
        y=lu.front()%1000;
        lu.pop();
        for(int i=0;i<4;i++)
        {
            cx=x+changex[i];
            cy=y+changey[i];
            if(cx<0||cx>4||cy<0||cy>4||mat[cx][cy])
                continue;
            else if(cx==4&&cy==4)
            {
                pre[cx][cy]=x*1000+y;
                break;
            }
            else if(pre[cx][cy]==cx*1000+cy)
            {//这个点没有搜索过
                pre[cx][cy]=x*1000+y;
                lu.push(cx*1000+cy);
            }
        }
    }
    stack <P> ans;
    ans.push(P(4,4));
    x=4,y=4;
    while(x||y)
    {
        cx=pre[x][y]/1000;
        cy=pre[x][y]%1000;
        ans.push(P(cx,cy));
        x=cx,y=cy;
    }
    while(!ans.empty())
    {
        printf("(%d, %d)\n",ans.top().x,ans.top().y);
        ans.pop();
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zuhiul

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值