網易 地牢逃脫 bfs

題目描述:

給定一個 n 行 m 列的地牢,其中 ‘.’ 表示可以通行的位置,‘X’ 表示不可通行的障礙,牛牛從 (x0 , y0 ) 位置出發,遍歷這個地牢,和一般的遊戲所不同的是,他每一步只能按照一些指定的步長遍歷地牢,要求每一步都不可以超過地牢的邊界,也不能到達障礙上。地牢的出口可能在任意某個可以通行的位置上。牛牛想知道最壞情況下,他需要多少步纔可以離開這個地牢。

輸入

每個輸入包含 1 個測試用例。每個測試用例的第一行包含兩個整數 n 和 m(1 <= n, m <= 50),表示地牢的長和寬。接下來的 n 行,每行 m 個字符,描述地牢,地牢將至少包含兩個 ‘.’。接下來的一行,包含兩個整數 x0, y0,表示牛牛的出發位置(0 <= x0 < n, 0 <= y0 < m,左上角的座標爲 (0, 0),出發位置一定是 ‘.’)。之後的一行包含一個整數 k(0 < k <= 50)表示牛牛合法的步長數,接下來的 k 行,每行兩個整數 dx, dy 表示每次可選擇移動的行和列步長(-50 <= dx, dy <= 50)

輸出

輸出一行一個數字表示最壞情況下需要多少次移動可以離開地牢,如果永遠無法離開,輸出 -1。以下測試用例中,牛牛可以上下左右移動,在所有可通行的位置.上,地牢出口如果被設置在右下角,牛牛想離開需要移動的次數最多,爲3次。

題意

Bfs.有個坑點的是,每次移動可以跨越障礙。

#include<iostream>
#include<algorithm>
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 55;
char map[maxn][maxn];
int vis[maxn][maxn];
int dir[maxn][2];
struct node{
    int x;
    int y;
    int step;
};
int n,m,cnt;
int flag;
int k;
int bfs(int x,int y)
{
    node temp;
    temp.x=x;
    temp.y=y;
    temp.step=0;
    queue<node> q;
    q.push(temp);
  //    cout<<cnt<<"    "<<endl;
    while(!q.empty())
    {
  
        node t;
        t=q.front();
        q.pop();
        int tx,ty,tstep;
        tx=t.x;
        ty=t.y;
        tstep=(t.step)+1;
        //cout<<tx<<" "<<ty<<"  step:"<<t.step<<endl;
        int nx,ny,nstep;
        for(int i=0;i<k;++i)
        {
            int nx = tx + dir[i][0];
            int ny = ty + dir[i][1];
            if(nx<0 || ny<0 || nx>=n || ny>=m || vis[nx][ny] || map[nx][ny]=='X')
            {
                continue;  
            }  

            vis[nx][ny]=1;
            cnt--;
            if(cnt==0)
            {
                //cout<<"end"<<endl;
                return tstep;
            }
            node ttt;
            ttt.x=nx;
            ttt.y=ny;
            ttt.step=tstep;
            q.push(ttt);
        }
        //system("pause");
    }
    return -1;
}
int main()
{
    while(cin>>n>>m)
    {
        memset(vis,0,sizeof(vis));
        for(int i=0;i<n;++i)
        {
            scanf("%s",map+i);
        }
        int x,y;        //牛牛的起點座標
        cin>>x>>y;
        cin>>k;
        for(int i=0;i<k;++i)
        {
            cin>>dir[i][0]>>dir[i][1];
        }
        vis[x][y]=1;
        cnt = -1;
        for(int i=0;i<n;++i)
        {
            for(int j=0;j<m;++j)
            {
                if(map[i][j]=='.')
                {
                    cnt++;
                }
            }
        }
        flag=0;
        cout<<bfs(x,y)<<endl;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章