hdu1180 詭異的樓梯

這道題其實就是在BFS基礎上的一個變形。要注意的細節是到達樓梯前若不能通過,可以選擇停留在原地等樓梯轉過來再過去,要把這種情況考慮進去。還有就是用當前的步數和樓梯的初始狀態來判斷樓梯此時的狀態。另外一點就是樓梯所在的位置不需要判重,因爲我們可能從下通過樓梯往上走,然後再通過這個樓梯從左往右。下面是AC代碼。


#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
int n,m,p[21][21],d[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
char a[21][21];
int sx,sy,ex,ey;
struct node
{
    int x,y,step;
};
int pd(int x,int y)
{
    if(x>0&&y>0&&x<=n&&y<=m&&!p[x][y]&&a[x][y]!='*')
        return 1;
    return 0;
}
void bfs()
{
    queue<node> q;
    node cur,next;
    cur.x=sx,cur.y=sy,cur.step=0;
    q.push(cur);
    while(!q.empty())
    {
        cur=q.front();
        //printf("%d %d %d\n",cur.x,cur.y,cur.step);
        q.pop();
        for(int i=0;i<4;i++)
        {
            next.x=cur.x+d[i][0];
            next.y=cur.y+d[i][1];
            next.step=cur.step+1;
            if(pd(next.x,next.y))
            {
                p[next.x][next.y]=1;
                if(a[next.x][next.y]=='|')
                {
                    p[next.x][next.y]=0;
                    if(i<=1&&next.step%2==1||i>1&&next.step%2==0)
                    {
                        next.x+=d[i][0];
                        next.y+=d[i][1];
                        if(p[next.x][next.y])
                            continue;
                        else
                            p[next.x][next.y]=1;
                    }
                    else
                    {
                        next.x=cur.x;
                        next.y=cur.y;
                    }
                }
                if(a[next.x][next.y]=='-')
                {
                    p[next.x][next.y]=0;
                    if(i>1&&next.step%2==1||i<=1&&next.step%2==0)
                    {
                        next.x+=d[i][0];
                        next.y+=d[i][1];
                        if(p[next.x][next.y])
                            continue;
                        else
                            p[next.x][next.y]=1;
                    }
                    else
                    {
                        next.x=cur.x;
                        next.y=cur.y;
                    }
                }
                if(next.x==ex&&next.y==ey)
                {
                    printf("%d\n",next.step);
                    return ;
                }
                q.push(next);
            }
        }
    }
}
int main()
{
    int i,j;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        getchar();
        for(i=1;i<=n;i++)
        {
            for(j=1;j<=m;j++)
            {
                scanf("%c",&a[i][j]);
                if(a[i][j]=='S')
                    sx=i,sy=j;
                if(a[i][j]=='T')
                    ex=i,ey=j;
            }
            getchar();
        }
        memset(p,0,sizeof(p));
        p[sx][sy]=1;
        bfs();
    }
    return 0;
}


發佈了30 篇原創文章 · 獲贊 1 · 訪問量 8184
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章