AcWing 1106. 山峰和山谷(Flood Fill)

题目链接:点击这里

在这里插入图片描述
在这里插入图片描述

注意山峰和山谷的判断,可能还有山坡呢

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

#define x first
#define y second

using namespace std;
typedef pair<int,int> PII;
const int N = 1010, M = N * N;

int n;
int h[N][N];
bool st[N][N];
PII q[M];

void bfs(int sx, int sy, bool& has_higher, bool& has_lower)
{
    int hh = 0, tt = -1;
    
    q[++tt] = {sx, sy};
    st[sx][sy] = true;
    
    while(hh <= tt)
    {
        PII t = q[hh++];
        
        for(int i = t.x - 1; i <= t.x + 1; ++i)
        {
            for(int j = t.y - 1; j <= t.y + 1; ++j)
            {
                if(i < 0 || i >= n || j < 0 || j >= n)  continue;
                
                if(h[i][j] != h[t.x][t.y])
                {
                    if(h[i][j] < h[t.x][t.y])   has_lower = true;
                    else    has_higher = true;
                    continue;
                }
                
                if(st[i][j])    continue;
                
                q[++tt] = {i, j};
                st[i][j] = true;
            }
        }
    }
}

int main()
{
    scanf("%d", &n);
    for(int i = 0; i < n; ++i)
    {
        for(int j = 0; j < n; ++j)
        {
            scanf("%d", &h[i][j]);
        }
    }
    
    int peak = 0, valley = 0;
    for(int i = 0; i < n; ++i)
    {
        for(int j = 0; j < n; ++j)
        {
            if(!st[i][j])
            {
                bool has_higher = false, has_lower = false;
                bfs(i, j, has_higher, has_lower);
                if(!has_higher) peak++;
                if(!has_lower)  valley++;
            }
        }
    }
    
    printf("%d %d\n", peak, valley);
    return 0;
}
发布了844 篇原创文章 · 获赞 135 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/qq_42815188/article/details/105058656