敌人入侵

敌人入侵

题目描述:

有一个城市是宽度为x,高度为y的网格图,(1,1)是左下角的格子。敌人刚开始占领了(sx,sy)格子,每天会攻占8个方向(上下左右,左上左下,右上右下)有人居住的所有格子。1天之后,又可以从这些被攻占的格子攻占其他格子。敌人想知道,多少天可以把该城市有人的地方都被攻占(数据保证都会被攻占)。
城市地图中,"."表示有人居住,而"*"表示没有人居住。

样例如下,这个宽度x=4,高度y=3的地图。
....
..*.
.**.

坐标表示如下(跟平面直角坐标系一样):

(1,3)(2,3)(3,3)(4,3)

(1,2)(2,2)(3,2)(4,2)

(1,1)(2,1)(3,1)(4,1)
如果敌人一开始在左下角(1,1),那么城市将会以如下态势发展:

        1519726678314225445.png

天数  0            1           2           3           4
敌人会在4天后占领整个城市。

输入格式:

第一行,四个整数x,y,sx,sy。分别表示城市的宽度,高度,敌人初始位置。
第2到第n+1行,每行有m个字符("."表示有人居住,"*"表示无人居住)。

输出格式:

一个数,表示多少天城市会被攻占。

样例输入:

4 3 1 1
....
..*.
.**.

样例输出:

4

提示:

 数据范围:1<=x,y<=100

扫描二维码关注公众号,回复: 2324298 查看本文章

时间限制:1000ms
空间限制:256MByte

 

#include<bits/stdc++.h>
using namespace std;

char m[105][105];
int bg[8][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}};
int n, k, sx, sy, s;

struct node{
    int x, y, s;
    node(int x1, int y1, int s1) : x(x1), y(y1), s(s1) {}
};

void t()
{
    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= k; j++) cout<<m[i][j];
        cout<<endl;
    }
    cout<<endl;
}
int main()
{
    queue<node> q;
    cin>>k>>n>>sy>>sx;
    sx = n - sx + 1;
    for(int i = 1; i <= n; i++){
        getchar();
        for(int j = 1; j <= k; j++) cin>>m[i][j];
    }
    q.push(node(sx, sy, 0));
    m[sx][sy] = 'A';
    while(!q.empty()){
        int x = q.front().x;
        int y = q.front().y;
        s = q.front().s;
        q.pop();
        for(int i = 0; i < 8; i++){
            int nx = x + bg[i][0];
            int ny = y + bg[i][1];
            if(nx > 0 && nx <= n && ny > 0 && ny <= k && m[nx][ny] == '.')
                m[nx][ny] = 'A', q.push(node(nx, ny, s + 1));
        }
    }
    cout<<s<<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/abs27/p/9354987.html