搜索中的记录步数

显示路径
poj.3984

#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
using namespace std;
int map[10][10],book[10][10];
int dir[4][2]={0,1,1,0,0,-1,-1,0};
struct node
{
    int x,y,step;  
}start,end,path[10][10];
int main ()
{
    for(int i=0;i<5;i++)
    {
        for(int j=0;j<5;j++)
        {
            scanf("%d",&map[i][j]);
        }
    }
    void bfs();
    void print(int a ,int b);
    end.x=4;
    end.y=4;
    start.x=0;
    start.y=0;
    start.step=0;
    memset(book,0,sizeof(book));
    book[0][0]=1;
    bfs();
}
void bfs()
{
    void print(int a ,int b,int t);
    queue <node> q;
    q.push(start);
    struct node head,tail;
    while(!q.empty())
    {
        head=q.front();
        q.pop();
        int i;
        if(head.x==4&&head.y==4)
            {
                print(4,4,head.step);
                printf("(4, 4)\n");//shu chu lu jing
                return;
            }
        for(i=0;i<4;i++)
        {
            tail.x=head.x+dir[i][0];
            tail.y=head.y+dir[i][1];
            tail.step=head.step+1;
            if(tail.x<0||tail.y<0||tail.x>4||tail.y>4||map[tail.x][tail.y]==1)
            continue;
            //printf("%d %d\n",tail.x,tail.y);
            if(map[tail.x][tail.y]==0&&book[tail.x][tail.y]==0)
            {
                book[tail.x][tail.y]=1;
                path[tail.x][tail.y].x=head.x;//chu cun qian yi bu
                path[tail.x][tail.y].y=head.y;
                q.push(tail);
            }
        }
    }
}
/*void print(int x,int y,int t)
 {
    int a,b,k=1;
    struct node put[100];
    while(x!=0||y!=0)
    {
        a=x;
        b=y;
        put[k].x=path[a][b].x;
        put[k++].y=path[a][b].y;
        x=path[a][b].x;
        y=path[a][b].y;
     }
     int i;
     for(int i=k-1;i>=1;i--)
     {
        printf("(%d, %d)\n",put[i].x,put[i].y);
     }
     printf("(4, 4)\n");
 }*/
 void print(int x,int y,int t)
 {
    if(t==1)
    printf("(0, 0)\n");
    else
    {
        print(path[x][y].x,path[x][y].y,--t);
        printf("(%d, %d)\n",path[x][y].x,path[x][y].y);
     }
 }
``
两种方法,重要的是自己看明白,想清楚广搜的原理即可
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值