HDU 1026 Ignatius and the Princess I 广度优先搜索(BFS)

来源:互联网 发布:桌面跳舞小人软件 编辑:程序博客网 时间:2024/05/18 10:39

题目链接: HDU 1026 Ignatius and the Princess I

题型:广搜
题意:在大小为n*m的地图中,求出从到点的最短时间,如果能到达要把路径打出来
分析:这题重要的就是打路径,说明每一个状态都要保存下来,但是如果顺序搜下去,这样就不好记下路径了,

      但是可以反过来搜索.同时也把前一个点(顺序走时是下一个点)的保存的位置记下来(这里类似于链表),

      然后再反过来打印.这时每打一个点时都可以找到下一个点. 

代码:

#include<iostream>#include<string>#include<cstring>#include<algorithm>#include<cstdio>#include<cmath>#include<cctype>#include<iomanip>#include<queue>using namespace std;const int maxn=1000000;int n,m,I,J,K;char map[105][105];int mint[105][105];///到达每个点的最小时间int dx[4]={0,0,1,-1};int dy[4]={1,-1,0,0};struct node{    int x,y;    int time;///到这点的时间    int next;///下一个点在M中的下标}M[maxn],st,ne;void BFS(){    I=0,J=1;    while(I!=J){        st=M[I];        for(int i=0;i<4;++i){            int x=st.x+dx[i];            int y=st.y+dy[i];            if(x<0||y<0||x>=n||y>=m||map[x][y]=='X')continue;            ne.x=x, ne.y=y, ne.time=st.time+1;            if(map[x][y]!='.')                ne.time+=map[x][y]-'0';            if(ne.time<mint[x][y]){                mint[x][y]=ne.time;                ne.next=I;///指向上一点在M中的下标,也就是                if(x==0&&y==0)K=J;  ///存下(0,0)点在M中的下标                M[J++]=ne;///入列            }        }        I++;    }}int main(){    while(~scanf("%d%d",&n,&m)){        for(int i=0;i<n;++i){            scanf("%s",map[i]);            for(int j=0;j<=m;++j)                mint[i][j]=maxn;///初始化为oo        }        M[0].x=n-1; M[0].y=m-1;        M[0].time=0; M[0].next=-1;        if(map[n-1][m-1]>='1'&&map[n-1][m-1]<='9')            M[0].time+=map[n-1][m-1]-'0';        mint[n-1][m-1]=M[0].time;        BFS();        if(mint[0][0]==maxn){///无法到达            printf("God please help our poor hero.\n");            printf("FINISH\n");            continue;        }        printf("It takes %d seconds to reach the target position, let me show you the way.\n",mint[0][0]);        st=M[K];        int t=1;        while(st.next>=0){            ne=M[st.next];            printf("%ds:(%d,%d)->(%d,%d)\n",t++,st.x,st.y,ne.x,ne.y);            if(map[ne.x][ne.y]>='1'&&map[ne.x][ne.y]<='9')                for(int i=0;i<map[ne.x][ne.y]-'0';++i)                    printf("%ds:FIGHT AT (%d,%d)\n",t++,ne.x,ne.y);            st=ne;        }        printf("FINISH\n");    }    return 0;}



原创粉丝点击