hdu 1026 Ignatius and the Princess I(BFS)

来源:互联网 发布:php微信第三方登录api 编辑:程序博客网 时间:2024/05/17 12:49

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1026

题       意:求从(0,0)到(n-1,m-1)点所花的时间,并将路径输出

思       路:由于要求路径,因此最好将其从终点开始到起点进行BFS遍历

代码如下:

#include <iostream>using namespace std;#include <string.h>#include <stdio.h>#include <queue>#include <algorithm>struct point{    int nx,ny;    char ch;} vis[120][120];int fig[120][120],visit[120][120];int n, m;int dx[4]= {1,-1,0,0},dy[4]= {0,0,-1,1};struct node{    int x,y,t;    friend bool operator < ( const node a, const node b )    {        return a.t > b.t;    }};int BFS(){    priority_queue<node>q;    while( !q.empty() )        q.pop();    node kai,dai;    visit[n-1][m-1]=1;    kai.x=n-1;    kai.y=m-1;    kai.t=0;    char c;    c = vis[kai.x][kai.y].ch;    if( c >= '1' && c <= '9' )    {        kai.t = c-'0';        fig[kai.x][kai.y]=c-'0';    }    q.push(kai);    while( !q.empty() )    {        kai=q.top();        q.pop();        if( kai.x == 0 && kai.y == 0 ) return kai.t;        for( int i = 0 ; i < 4; i ++ )        {            dai.x = kai.x + dx[i];            dai.y = kai.y + dy[i];            if( dai.x >=0 && dai.x < n && dai.y >= 0 && dai.y < m && visit[dai.x][dai.y] == 0 && vis[dai.x][dai.y].ch != 'X' )            {                visit[dai.x][dai.y]=1;                if( vis[dai.x][dai.y].ch >= '0' && vis[dai.x][dai.y].ch <= '9' )                {                    dai.t = kai.t + vis[dai.x][dai.y].ch - '0' + 1;                    fig[dai.x][dai.y] = vis[dai.x][dai.y].ch - '0';                }                else dai.t = kai.t + 1;                q.push(dai);                vis[dai.x][dai.y].nx=kai.x;                vis[dai.x][dai.y].ny=kai.y;            }        }    }    return -1;}int main(){    while( scanf ( "%d %d", &n, &m ) != EOF )    {        for( int i = 0 ; i < n; i ++ )            for( int j = 0; j < m; j ++ )                scanf ( " %c", &vis[i][j].ch );        memset(visit,0,sizeof(visit));        memset(fig,0,sizeof(fig));        int ans = BFS();        if( ans > -1 )        {            int cnt = 1, x = 0, y = 0;            printf("It takes %d seconds to reach the target position, let me show you the way.\n",ans);            while ( cnt <= ans )            {                int nex,ney;                nex = vis[x][y].nx;                ney = vis[x][y].ny;                //cout<<nex<<" "<<ney<<endl;                printf("%ds:(%d,%d)->(%d,%d)\n",cnt++,x,y,nex,ney);                for( int j = 1; j <= fig[nex][ney]; j ++ )                    printf("%ds:FIGHT AT (%d,%d)\n",cnt++,nex,ney);                x = nex;                y = ney;            }        }        else printf("God please help our poor hero.\n");        printf("FINISH\n");    }    return 0;}


 

0 0
原创粉丝点击