poj3984 迷宫问题(bfs+路径)

本文介绍了一种使用栈和广度优先搜索算法解决从5x5矩阵左上角到右下角路径寻找问题的方法。通过细致的实现,确保了算法能够正确找到一条有效的路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


http://poj.org/problem?id=3984

题意:给你个5x5矩阵,输出左上角到右下角的路径。


思路:用栈记录,细心。


#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <queue>
#include <stack>

using namespace std;

typedef long long LL;

const int N = 10;
const int INF = 0x3f3f3f3f;

int G[N][N];
bool vis[N][N];
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

struct node
{
    int x, y, step, prex, prey;
    friend bool operator < (const node &a, const node &b)
    {
        return a.step > b.step;
    }
};

node path[N][N];

bool check(int x, int y)
{
    if(x>=0 && x<=4 && y>=0 && y<=4 && !vis[x][y] && G[x][y]!=1) return true;
    else return false;
}

void bfs(int x, int y)
{
    memset(vis, false, sizeof(vis));
    priority_queue<node>que;
    node s;
    s.x = x;
    s.y = y;
    s.step = 0;
    vis[x][y] = true;
    que.push(s);
    while(!que.empty())
    {
        node tmp = que.top();
        que.pop();
        if(tmp.x==4 && tmp.y==4)
        {
            path[tmp.x][tmp.y] = tmp;
            break;
        }//注意终止顺序
        for(int i = 0; i < 4; i++)
        {
            node tmp2;
            tmp2 = tmp;
            tmp2.x += dir[i][0];
            tmp2.y += dir[i][1];
            if(check(tmp2.x, tmp2.y))
            {
                vis[tmp2.x][tmp2.y] = true;
                tmp2.prex = tmp.x;
                tmp2.prey = tmp.y;
                que.push(tmp2);//进队列顺序前要把前驱处理好
                path[tmp2.x][tmp2.y] = tmp2;
            }
        }
    }
}

void Print()
{
    stack<node>sta;
    node now = path[4][4];
    sta.push(now);
    while(1)
    {
        now = path[now.prex][now.prey];
        sta.push(now);
        if(now.x==0 && now.y==0) break;
    }
    while(!sta.empty())
    {
        now = sta.top();
        sta.pop();
        printf("(%d, %d)\n", now.x, now.y);
    }
}


int main()
{
 //   freopen("in.txt", "r", stdin);
    for(int i = 0; i < 5; i++)
        for(int j = 0; j < 5; j++)
        {
            cin >> G[i][j];
        }
    bfs(0, 0);
    Print();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值