[AcWing 1106] 山峰和山谷
Flood Fill
点击查看代码
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1000 + 10;
#define x first
#define y second
int n;
int g[N][N];
bool st[N][N];
int dx[] = {0, -1, 0, 1};
int dy[] = {-1, 0, 1, 0};
void bfs(int x, int y, bool &high, bool &low)
{
queue<pair<int,int>> q;
q.push({x, y});
st[x][y] = true;
while (q.size()) {
auto t = q.front();
q.pop();
for (int i = t.x - 1; i <= t.x + 1; i ++)
for (int j = t.y - 1; j <= t.y + 1; j ++) {
if (t.x == i && t.y == j)
continue;
if (i < 1 || i > n || j < 1 || j > n)
continue;
if (g[i][j] != g[t.x][t.y]) {
if (g[i][j] > g[t.x][t.y])
high = true;
else
low = true;
}
else if (!st[i][j]) {
q.push({i, j});
st[i][j] = true;
}
}
}
}
void solve()
{
cin >> n;
for (int i = 1; i <= n; i ++)
for (int j = 1; j <= n; j ++)
cin >> g[i][j];
int peak = 0, valley = 0;
for (int i = 1; i <= n; i ++)
for (int j = 1; j <= n; j ++)
if (!st[i][j]) {
bool high = false, low = false;
bfs(i, j, high, low);
if (!high)
peak ++;
if (!low)
valley ++;
}
cout << peak << ' ' << valley << endl;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
solve();
return 0;
}
- 当遇到没有标记过的块时,对其做 \(BFS\),同时记录周围有无更高的或者更低的,如果没有更高的,说明这一块所属的区域是山峰,如果没有更低的,说明这一块所属的区域是山谷