牛客小白月赛4 C 病菌感染 dfs

链接:https://www.nowcoder.com/acm/contest/134/C
来源:牛客网

题目描述

铁子和顺溜上生物课的时候不小心将几滴超级病菌滴到了培养皿上,这可急坏了他们。
培养皿可以被看成一个n*n的方格,最初病菌滴在了这n*n的格子中的某些格子,病菌的传染方式是这样的,如果一个方格与两个或多个被感染的方格相邻(两个方格相邻当且仅当它们只有一条公共边),
那么它就会被感染。现在铁子和顺溜想知道,最终所有的方格会不会都被感染。

输入描述:

第一行两个整数n,m。n表示方格的规格,m表示最初病菌所在的格子数。(1 ≤ n ≤ 1000, 0 < m < n)。
接下来m行每行两个整数xi,yi表示第xi行的第yi个格子有病菌。
数据保证不会有两个病菌初始时在同一个格子。

输出描述:

如果最终所有的方格都会被感染,输出 YES。
否则输出 NO。
示例1

输入

复制
3 2
1 2
2 2

输出

复制
NO

分析:考虑每个病菌只会影响到周围上下左右四个点,且只能在他上下左右四个斜方向上有病菌的情况下,但是这些被感染的点还会继续影响下面的,所以直接dfs找出所有可能被感染的点就可以了
AC代码:
#include <map>
#include <set>
#include <stack>
#include <cmath>
#include <queue>
#include <cstdio>
#include <vector>
#include <string>
#include <bitset>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
#define ls (r<<1)
#define rs (r<<1|1)
#define debug(a) cout << #a << " " << a << endl
using namespace std;
typedef long long ll;
const ll maxn = 1e3+10;
const double eps = 1e-8;
const ll mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const double pi = acos(-1.0);
ll mapn[maxn][maxn];
ll n, m;
void dfs( ll x, ll y ) {
    if( x-1 > 0 && y-1 > 0 && mapn[x-1][y-1] ) {
        if( !mapn[x][y-1] ) {
            mapn[x][y-1] = 1;
            dfs(x,y-1);
        }
        if( !mapn[x-1][y] ) {
            mapn[x-1][y] = 1;
            dfs(x-1,y);
        }
    }
    if( x+1 <= n && y-1 > 0 && mapn[x+1][y-1] ) {
        if( !mapn[x][y-1] ) {
            mapn[x][y-1] = 1;
            dfs(x,y-1);
        }
        if( !mapn[x+1][y] ) {
            mapn[x+1][y] = 1;
            dfs(x+1,y);
        }
    }
    if( x+1 <= n && y+1 <= n && mapn[x+1][y+1] ) {
        if( !mapn[x+1][y] ) {
            mapn[x+1][y] = 1;
            dfs(x+1,y);
        }
        if( !mapn[x][y+1] ) {
            mapn[x][y+1] = 1;
            dfs(x,y+1);
        }
    }
    if( x-1 > 0 && y+1 <= n && mapn[x-1][y+1] ) {
        if( !mapn[x][y+1] ) {
            mapn[x][y+1] = 1;
            dfs(x,y+1);
        }
        if( !mapn[x-1][y] ) {
            mapn[x-1][y] = 1;
            dfs(x-1,y);
        }
    }
}
int main() {
    ios::sync_with_stdio(0);
    cin >> n >> m;
    memset(mapn,0,sizeof(mapn));
    vector<pair<ll,ll> > e;
    while( m -- ) {
        ll x, y;
        cin >> x >> y;
        mapn[x][y] = 1;
        e.push_back(make_pair(x,y));
    }
    for( ll i = 0; i < e.size(); i ++ ) {
        dfs(e[i].first,e[i].second);
    }
    bool flag = true;
    for( ll i = 1; i <= n; i ++ ) {
        for( ll j = 1; j <= n; j ++ ) {
            if( !mapn[i][j] ) {
                flag = false;
                break;
            }
        }
    }
    if( flag ) {
        cout << "YES" << endl;
    } else {
        cout << "NO" << endl;
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/l609929321/p/9531922.html