题目描述:

给定一个 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;
}
Last modification:September 19th, 2019 at 12:09 am
如果觉得我的文章对你有用,请随意赞赏