题解:

spfa

允许多次进队

代码:

#include<bits/stdc++.h> 
using namespace std;
struct que{int x,y,dire,dist;}now,wrk;
bool operator<(const que &a,const que &b){return a.dist>b.dist;}
priority_queue <que> q;
const int mx[4]={0,1,0,-1},my[4]={1,0,-1,0};
int n,m,sx,sy,ex,ey,mrk[110][110],dist[110][110][4];
int main()
{
    scanf("%d%d",&m,&n);
    for (int i=1;i<=n;i++)
     for (int j=1;j<=m;j++)
      {
        char ch=getchar();
        while (ch!='C'&&ch!='.'&&ch!='*')ch=getchar();
        if (ch=='*')mrk[i][j]=1;
        if (ch=='C')
         {
             if (!sx){sx=i;sy=j;}
            else {ex=i;ey=j;}
         }
      }
    memset(dist,127,sizeof(dist));
    now.x=sx;now.y=sy;now.dist=0;
    for (int i=0;i<4;i++)
     {
        now.dire=i;
        q.push(now);
        dist[sx][sy][i]=0;
     }
    while (!q.empty())
     {
        now=q.top();q.pop();
        int k=now.dire;
        wrk=now;
        while (wrk.x+mx[k]>=1&&wrk.x+mx[k]<=n&&wrk.y+my[k]>=1
        &&wrk.y+my[k]<=m&&!mrk[wrk.x+mx[k]][wrk.y+my[k]]
        &&dist[wrk.x+mx[k]][wrk.y+my[k]][k]>wrk.dist)
         {
            wrk.x+=mx[k];wrk.y+=my[k];
            dist[wrk.x][wrk.y][k]=dist[now.x][now.y][k];
            q.push(wrk);
         }
        wrk=now;wrk.dist++;
        for (int k=0;k<4;k++)
        if(dist[now.x][now.y][k]>now.dist+1)
         {
            dist[now.x][now.y][k]=now.dist+1;
            wrk.dire=k;
            q.push(wrk);
         }
     }
    int ans=1e9;
    for (int k=0;k<4;k++)
      ans=min(ans,dist[ex][ey][k]);
    printf("%d\n",ans);
}

 

posted on 2018-02-06 15:19  宣毅鸣  阅读(112)  评论(0编辑  收藏  举报