Hdoj 1026 Ignatius and the Princess I

题目传送门

///bfs跑路,dfs记录路径
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#include<iostream>
using namespace std;

char maze[105][105];
int maze1[105][105],maze2[105][105];
bool vis[105][105];
int dir[][2]={{0,1},{0,-1},{-1,0},{1,0}};
int n,m;
struct node{
   int x,y;
   int time;
   friend bool operator<(const node &a,const node &b)
   {
       return a.time>b.time;
   }
};

bool check(int x,int y)
{
    if(x>=0&&x<n&&y>=0&&y<m&&maze[x][y]!='X')
        return true;
    return false;
}

int bfs();
void dfs(int x,int y,int num);

int main()
{
    int ans;
    while(~scanf("%d%d",&n,&m))
    {
        for(int i=0;i<n;i++)
            scanf("%s",maze[i]);
        memset(maze1,0,sizeof(maze1));
        memset(maze2,0,sizeof(maze2));
        memset(vis,false,sizeof(vis));
        ans=bfs();
        if(ans==-1)
        {
            puts("God please help our poor hero.");
        }
        else
        {
            printf("It takes %d seconds to reach the target position, let me show you the way.\n",ans);
            dfs(n-1,m-1,ans);///记录bfs走的路径表
        }
        puts("FINISH");
    }
    return 0;
}

int bfs()
{
    node st,en;
    priority_queue<node>qq;
    st=(node){0,0,0};
    vis[0][0]=true;
    qq.push(st);
    while(!qq.empty())
    {
        st=qq.top();
        qq.pop();
        if(st.x==n-1&&st.y==m-1)
        {
            return st.time;
        }
        for(int i=0;i<4;i++)
        {
            en.x=st.x+dir[i][0];
            en.y=st.y+dir[i][1];
            if(check(en.x,en.y)&&!vis[en.x][en.y])
            {
                maze1[en.x][en.y]=st.x;
                maze2[en.x][en.y]=st.y;
                if(maze[en.x][en.y]=='.')
                    en.time=st.time+1;
                else
                    en.time=st.time+(maze[en.x][en.y]-'0')+1;
                vis[en.x][en.y]=true;
                qq.push(en);
            }
        }
    }
    return -1;
}

void dfs(int x,int y,int num)
{
    if(maze1[x][y]+maze2[x][y])
    {
        if(maze[x][y]=='.')
            dfs(maze1[x][y],maze2[x][y],num-1);
        else
            dfs(maze1[x][y],maze2[x][y],num-1-(maze[x][y]-'0'));
    }
    if(maze[x][y]=='.')
        printf("%ds:(%d,%d)->(%d,%d)\n",num,maze1[x][y],maze2[x][y],x,y);
    else
    {
        printf("%ds:(%d,%d)->(%d,%d)\n",num-maze[x][y]+'0',maze1[x][y],maze2[x][y],x,y);
        for(int i=maze[x][y]-'0';i>=1;i--)
        printf("%ds:FIGHT AT (%d,%d)\n",num+1-i,x,y);
    }
}

你可能感兴趣的:(Hdoj 1026 Ignatius and the Princess I)