poj 3984 迷宫问题(广搜)

本文介绍了一种使用广度优先搜索(BFS)算法解决5x5矩阵中从起点到终点最短路径的问题。通过定义节点结构和方向数组,实现了从(0,0)到(4,4)的最短路径搜索,并记录了路径信息。

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

题目地址

题目大意:一个5X5的矩阵,0表示可以走,1表示不能走,输出从(0,0)到(4,4)的最短走法

解题思路:首先想到是广搜,用队列实现,从(0,0)开始,第一次遇到(4,4)就停止搜索,因为要输出走法,就要不断记录前一个点,不断自身递归调用,直到输出第一个点,因为第一个点的pre为-1,所以要手动输出,最后一个点还没有加入队列,也需要手动输出

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <string>
#include <queue>
#include <vector>
#include <list>
#include <stack>
#include <map>
#include <set>

using namespace std;

const int dir[4][2] = {{-1,0},{1,0},{0,1},{0,-1}};

struct Node
{
    int x,y,pre;
}q[100];

int head = 0,rear = 1;
int a[5][5];

void print(int i)
{
    if(q[i].pre != -1)
    {
        print(q[i].pre);
        printf("(%d, %d)\n",q[i].x,q[i].y);
    }
}

void bfs(int x1,int y1)
{
   q[head].x = x1;
   q[head].y = y1;
   q[head].pre = -1;
   while(head < rear)
   {
       for(int i = 0; i < 4; i++)
       {
           int xx = q[head].x+dir[i][0];
           int yy = q[head].y+dir[i][1];
           if(xx<0 || xx>4 || yy<0 || yy>4 || a[xx][yy])    continue;
           else
           {
               a[xx][yy] = 1;
               q[rear].x = xx;
               q[rear].y = yy;
               q[rear].pre = head;
               rear++;//入队
           }
           if(xx==4 && yy==4)   print(head);
       }
       head++;//出队
   }
}

int main()
{
    for(int i = 0; i < 5; i++)
        for(int j = 0; j < 5; j++)
            scanf("%d",&a[i][j]);
    printf("(0, 0)\n");
    bfs(0,0);
    printf("(4, 4)\n");
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值