hdu 1026 Ignatius and the Princess I (深搜)

//Time 906ms, Memory 384K
#include<stdio.h>

#include<string.h>

int vis[110][110],dx[4]={0,1,0,-1},dy[4]={1,0,-1,0},n,m,t,min,num,road[6000],rd[6000];

char map[110][110];

void f(int x,int y)

{

    int i,nx,ny,p;

    if(x==n-1 && y==m-1)

    {

        for(i=0;i<num;i++)

            road[i]=rd[i];

        min=num;return;

    }

    if((vis[n-1][m-1]!=-1 && n+m-x-y-2+t>=vis[n-1][m-1]) || num>6000) return;

    num++;

    for(i=0;i<4;i++)

    {

        nx=x+dx[i];ny=y+dy[i];

        if(nx<0 || ny<0 || nx>n-1 || ny>m-1 || map[nx][ny]=='X') continue;

        else if(map[nx][ny]=='.') p=1;

        else p=map[nx][ny]-47;

        if(vis[nx][ny]!=-1 && t+p>=vis[nx][ny]) continue;

        if((ny+1<m && vis[nx][ny+1]!=-1 && vis[nx][ny+1]<vis[x][y]) || (ny-1>=0 && vis[nx][ny-1]!=-1 && vis[nx][ny-1]<vis[x][y]) || (nx-1>=0 && vis[nx-1][ny]!=-1 && vis[nx-1][ny]<vis[x][y]) || (nx+1<n && vis[nx+1][ny]!=-1 && vis[nx+1][ny]<vis[x][y])) continue;

        t+=p;vis[nx][ny]=t;rd[num-1]=nx*m+ny;

        f(nx,ny);t-=p;

    }

    num--;

}

int main()

{

    int i,x=0,y=0,x1,y1,x2,y2,t1,a;

    while(scanf("%d%d\n",&n,&m)==2)

    {

        memset(vis,-1,sizeof(vis));

        memset(road,0,sizeof(road));

        num=t=0;t1=0;

        for(i=0;i<n;i++)

            gets(map[i]);

        vis[0][0]=0;

        f(x,y);x2=y2=0;

        if(vis[n-1][m-1]==-1)

        {

            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",vis[n-1][m-1]);

        for(i=0;i<min;i++)

        {

            x1=road[i]/m;y1=road[i]%m;t1++;

            printf("%ds:(%d,%d)->(%d,%d)\n",t1,x2,y2,x1,y1);

            if(map[x1][y1]<='9' && map[x1][y1]>='1')

            {

                a=map[x1][y1]-48;

                while(a--) printf("%ds:FIGHT AT (%d,%d)\n",++t1,x1,y1);

            }

            x2=x1;y2=y1;

        }

        printf("FINISH\n");

    }

    return 0;

}


你可能感兴趣的:(HDU)