poj 3182 The Grove bfs

來源:互聯網
上載者:User

#include <iostream>#include <cstdio>#include <cstring>using namespace std;const int maxn=5e1+9,inf=1e9;char a[maxn][maxn],now[maxn][maxn];int dist[maxn][maxn],d[maxn][maxn],quex[1111111],quey[1111111];int n,m;void init(){    memset(a,0,sizeof(a));    memset(now,0,sizeof(now));}void bfs(int x,int y,int dist[maxn][maxn]){    bool visit[maxn][maxn];    memset(dist,50,sizeof(dist));    memset(visit,0,sizeof(visit));    dist[x][y]=0;    int front=1,end=0;    quex[++end]=x;    quey[end]=y;    visit[x][y]=1;    while(front<=end)    {        int nowx=quex[front],nowy=quey[front++];        int tox,toy;        for(int i=-1;i<=1;i++)        for(int j=-1;j<=1;j++)        {            tox=nowx+i;            toy=nowy+j;            if(tox>n||tox<1) continue;            if(toy>m||toy<1) continue;            if(now[tox][toy]=='X') continue;            if(!visit[tox][toy])            {                visit[tox][toy]=1;                dist[tox][toy]=dist[nowx][nowy]+1;                quex[++end]=tox;                quey[end]=toy;            }        }    }}int main(){//    freopen("in.txt","r",stdin);    while(scanf("%d %d",&n,&m)!=EOF)    {        init();        int sx,sy,lowx,lowy;        for(int i=1;i<=n;i++)        for(int j=1;j<=m;j++)        {            char tmp;            tmp=getchar();            if(tmp==' '||tmp=='\n')  j--;            else a[i][j]=tmp;            if(tmp=='*') sx=i,sy=j;        }        for(int i=1;i<=n;i++)        for(int j=1;j<=m;j++)        if(a[i][j]=='X')        {            lowx=i;            lowy=j;            i=n+1;            break;        }        for(int i=1;i<=n;i++) strcpy(now[i]+1,a[i]+1);        for(int i=lowx;i>=1;i--)        now[i][lowy-1]='X';        bfs(sx,sy,dist);        int upx=lowx,upy;        for(int j=m;j>=1;j--)        if(a[upx][j]=='X')        {            upy=j;            break;        }        for(int i=1;i<=n;i++) strcpy(now[i]+1,a[i]+1);        for(int i=upx;i>=1;i--)        now[i][upy+1]='X';        int ans=inf;        for(int i=lowx-1;i>=1;i--)        {            bfs(i,lowy,d);            ans=min(ans,dist[i][lowy]+d[sx][sy]);        }        cout<<ans<<endl;    }    return 0;}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.