搜索中的记录步数

来源:互联网 发布:数据汇集平台 编辑:程序博客网 时间:2024/06/05 19:36

显示路径
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);     } }``
两种方法,重要的是自己看明白,想清楚广搜的原理即可
原创粉丝点击