hdu 1026 Ignatius and the Princess I(BFS)

只需要记录路径就行了,对于花费的时间,可以用优先队列来维护。难得的1A。

#include
#include
#include
using namespace std;
#define N 105
int mark[N][N],vis[N][N];
int n,m;
char s[N];
int cnt;
int dir[4][2]={{0,1},{1,0},{-1,0},{0,-1}};
struct node
{
    int x,y;
    int cnt;
    friend bool operator<(node a,node b)
    {
        return a.cnt>b.cnt;
    };
}q[N*N];
struct point
{
    int prex,prey;
}ans[N][N];
int judge(int x,int y)
{
    if(x>=1&&x<=m&&y>=1&&y<=n&&mark[x][y]!=-1&&vis[x][y]==0) return 1;
    return 0;
}
int BFS()
{
    node cur,next;
    cur.x=1;cur.y=1;cur.cnt=0;vis[1][1]=1;
    priority_queueq;
    q.push(cur);
    while(!q.empty())
    {
        cur=q.top();
        q.pop();
        for(int i=0;i<4;i++)
        {
            next.cnt=cur.cnt+1;
            next.x=cur.x+dir[i][0];
            next.y=cur.y+dir[i][1];
            if(judge(next.x,next.y))
            {
                if(mark[next.x][next.y]!=0) next.cnt+=mark[next.x][next.y];
                vis[next.x][next.y]=1;
                ans[next.x][next.y].prex=cur.x;ans[next.x][next.y].prey=cur.y;
                if(next.x==m&&next.y==n) return next.cnt;
                q.push(next);
            }
        }
    }
    return -1;
}
void print(int x,int y)
{
    if(x==1&&y==1) return ;
    print(ans[x][y].prex,ans[x][y].prey);
    printf("%ds:(%d,%d)->(%d,%d)\n",cnt++,ans[x][y].prex-1,ans[x][y].prey-1,x-1,y-1);
    if(mark[x][y]==0) return ;
    while(mark[x][y]--) printf("%ds:FIGHT AT (%d,%d)\n",cnt++,x-1,y-1);
    return ;
}
int main()
{
    while(scanf("%d%d",&m,&n)!=EOF)
    {
        getchar();
        for(int i=1;i<=m;i++)
        {
            gets(s+1);
            for(int j=1;j<=n;j++)
            {
                if(s[j]=='.') mark[i][j]=0;
                else if(s[j]=='X') mark[i][j]=-1;
                else mark[i][j]=s[j]-'0';
            }
        }
        int answer;
        memset(vis,0,sizeof(vis));
        memset(ans,0,sizeof(ans));
        answer=BFS();
        if(answer==-1) printf("God please help our poor hero.\n");
        else
        {
            printf("It takes %d seconds to reach the target position, let me show you the way.\n",answer);
            cnt=1;
            print(m,n);
        }
        printf("FINISH\n");
    }
    return 0;
}


你可能感兴趣的:(搜索,搜索)