Ignatius and the Princess I(带路径的广搜)

题目
题意:给你一个图,从(0,0)出发,到达(n-1,m-1),X不能走,’.'可以走,但需要耗时1;数字是需要额外消耗时间,例如到达有个2这个点需要耗费3,问最少要多少时间;
代码:

#include<bits/stdc++.h>
using namespace std;
char ans[205][205];
int n,m,sumt;
int flag[205][205];
bool book[205][205];
int temp[4][2]={1,0,-1,0,0,1,0,-1};
struct Node {
    int x,y,t;
    friend bool operator < (Node a,Node b) {
        return a.t>b.t;
    }
};

int bfs() {
    Node now,next;
    priority_queue<Node> Q;
    while(!Q.empty()) Q.pop();
    now.x=now.y=now.t=0;
    if(ans[0][0]>'0'&&ans[0][0]<='9') now.t=ans[0][0]-'0';
    Q.push(now),book[0][0]=false;
    while(!Q.empty()) {
        now=Q.top();
        Q.pop();
        if(now.x==n-1&&now.y==m-1) return now.t;
        for(int i=0;i<4;i++) {
            next.x=now.x+temp[i][0];
			next.y=now.y+temp[i][1];
            if(next.x>=0&&next.x<n&&next.y>=0&&next.y<m&&book[next.x][next.y]&&ans[next.x][next.y]!='X') {
                if(ans[next.x][next.y]=='.') next.t=now.t+1;
                else next.t=now.t+(ans[next.x][next.y]-'0')+1;
                flag[next.x][next.y]=i+1;
                book[next.x][next.y]=false;
                Q.push(next);
            }
        }
    }
    return -1;
}

void print(int x,int y) {
    if(!flag[x][y]) return ;
    int next_x=x-temp[flag[x][y]-1][0];
    int next_y=y-temp[flag[x][y]-1][1];
    print(next_x,next_y);
    cout<<sumt++<<"s:("<<next_x<<','<<next_y<<")->("<<x<<','<<y<<')'<<endl;
    if(ans[x][y]>'0'&&ans[x][y]<='9') {
        int sum=ans[x][y]-'0';
        while(sum--) {
            cout<<sumt++<<"s:FIGHT AT ("<<x<<','<<y<<')'<<endl;
        }
    }
    return ;
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    while(cin>>n>>m&&n&&m) {
        memset(ans,0,sizeof(ans));
        memset(flag,0,sizeof(flag));
        for(int i=0;i<n;i++) {
            for(int j=0;j<m;j++) {
                cin>>ans[i][j];
            }
        }
        memset(book,true ,sizeof(book));
        int cnt=bfs();
        if(cnt==-1) cout<<"God please help our poor hero."<<endl;
        else {
                sumt=1;
                cout<<"It takes "<<cnt<<" seconds to reach the target position, let me show you the way."<<endl;
                if(ans[0][0]>'0'&&ans[0][0]<'9') {
                int sum=ans[0][0]-'0';
                while(sum--) {
                    cout<<sumt++<<"s:FIGHT AT ("<<0<<','<<0<<')'<<endl;
                }
            }
            print(n-1,m-1);
        }
        cout<<"FINISH"<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/G191018/article/details/88919233