poj3984bfs

8 篇文章 0 订阅
#include<cstdio>
#include<iostream>

#define N 5
using namespace std;

struct note
{
    int x,y,pre;//存放坐标,前一个节点的位置
}que[100];

int maze[N][N];
int Nx[4]={1,-1,0,0};
int Ny[4]={0,0,-1,1};
int start=0,end=1;//用数组模拟一个队列

void print(int s)
{
    if(que[s].pre!=-1)
    {//递归输出
        print(que[s].pre);//根据查找前一个的位置来递归
        cout<<"("<<que[s].x<<", "<<que[s].y<<")"<<endl;
    }
}

void bfsMaze(int x,int y)
{
    que[start].pre=-1;
    que[start].x=x;
    que[start].y=y;
    while(start<end)
    {
        for(int i=0;i<4;i++)
        {
            int a=Nx[i]+que[start].x;
            int b=Ny[i]+que[start].y;
            if(a<0 || b<0 || a>=N || b>=N || maze[a][b])//如果出界或者遇到墙
                continue;
            else
            {
                maze[a][b]=-1;//设置已经访问过
                //入队
                que[end].pre=start;
                que[end].x=a;
                que[end].y=b;
                end++;//数组大小
            }
            if(a==N-1 && b==N-1)
                print(start);
        }
        start++;
    }

}
int main()
{
    int i,j;
    for(i=0;i<N;i++)
        for(j=0;j<N;j++)
            scanf("%d",&maze[i][j]);
    cout<<"(0, 0)"<<endl;
    bfsMaze(0,0);
    cout<<"("<<N-1<<", "<<N-1<<")"<<endl;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值