Ignatius and the Princess I (BFS)

/*
Ignatius and the Princess I
HDU - 1026 
https://vjudge.net/problem/HDU-1026
*/
#include <bits/stdc++.h>
using namespace std;
#define maxn 1010
#define INF 0X3f3f3f3f
char mp_c[maxn][maxn];
int mp[maxn][maxn];
int mp_[maxn][maxn];
int mp_1[maxn][maxn];
int n,m;
struct node{
  int x,y;
};
void init(){
  for(int i=0;i<n;i++){
    for(int j=0;j<m;j++){
      if(mp_c[i][j]=='X') mp[i][j]=INF;
      else if(mp_c[i][j]>='0'&&mp_c[i][j]<='9') mp[i][j]=-(mp_c[i][j]-'0');
      else mp[i][j]=0;
    }
  }
  for(int i=0;i<n;i++){
    for(int j=0;j<m;j++){
      mp_[i][j]=mp_1[i][j]=mp[i][j];
    }
  }
}
int bfs(){
  queue<node> q;
  q.push((node){0,0});
  while(!q.empty()){
    node aa=q.front();
    q.pop();
    int x=aa.x;
    int y=aa.y;
    if(x==n-1&&y==m-1&&mp_[x][y]>=0) return mp[x][y]-1;
    if(mp_[x][y]<0){
      mp[x][y]++;
      mp_[x][y]++;
      q.push((node){x,y});
    }else{
      if(x-1>0&&mp[x-1][y]<=0){
        mp[x-1][y]=mp[x][y]+1;
        q.push((node){x-1,y});
      }
      if(x+1<n&&mp[x+1][y]<=0){
        mp[x+1][y]=mp[x][y]+1;
        q.push((node){x+1,y});
      }
      if(y-1>0&&mp[x][y-1]<=0){
        mp[x][y-1]=mp[x][y]+1;
        q.push((node){x,y-1});
      }
      if(y+1<m&&mp[x][y+1]<=0){
        mp[x][y+1]=mp[x][y]+1;
        q.push((node){x,y+1});
      }
    }
  }
  return 0;
}
stack<node> st;
void dfs(int x,int y){
  if(x-1>=0&&mp[x][y]==mp[x-1][y]+1-mp_1[x][y]){
    st.push((node){x-1,y});
    dfs(x-1,y);
  }else if(x+1<n&&mp[x][y]==mp[x+1][y]+1-mp_1[x][y]){
    st.push((node){x+1,y});
    dfs(x+1,y);
  }else if(y-1>=0&&mp[x][y]==mp[x][y-1]+1-mp_1[x][y]){
    st.push((node){x,y-1});
    dfs(x,y-1);
  }else if(y+1<m&&mp[x][y]==mp[x][y+1]+1-mp_1[x][y]){
    st.push((node){x,y+1});
    dfs(x,y+1);
  }
}
int main(){
  while(~scanf("%d %d", &n, &m)){
    for(int i=0;i<n;i++){
      scanf("%s", mp_c[i]);
    }
    init();
    mp[0][0]=1;
    int ans=bfs();
    if(ans){
      printf("It takes %d seconds to reach the target position, let me show you the way.\n", ans);
      st.push((node){n-1,m-1});
      dfs(n-1,m-1);
      int num=1;
      node a=st.top();
      st.pop();
      while(!st.empty()){
        node b=st.top();
        st.pop();
        printf("%ds:(%d,%d)->(%d,%d)\n", num, a.x, a.y, b.x, b.y);
        num++;
        if(mp_1[b.x][b.y]<0){
          for(int i=0;i<-mp_1[b.x][b.y];i++){
            printf("%ds:FIGHT AT (%d,%d)\n", num, b.x, b.y);
            num++;
          }
        }
        a=b;
      }
    }else{
      printf("God please help our poor hero.\n");
    }
    printf("FINISH\n");
  }
  return 0;
}


发布了70 篇原创文章 · 获赞 22 · 访问量 6478

猜你喜欢

转载自blog.csdn.net/weixin_44410512/article/details/104054996