【题目描述】
给定一个 n×n
的网格状地图,每个方格 (i,j)有一个高度 w(i, j)
。如果两个方格有公共顶点,则它们是相邻的。
定义山峰和山谷如下:
均由地图上的一个连通块组成;
所有方格高度都相同;
周围的方格(即不属于山峰或山谷但与山峰或山谷相邻的格子)高度均大于山谷的高度,或小于山峰的高度。
求地图内山峰和山谷的数量。特别地,如果整个地图方格的高度均相同,则整个地图既是一个山谷,也是一个山峰。
【输入】
第一行一个整数n(2≤n≤1000)
,表示地图的大小。
接下来 n
行每行 n 个整数表示地图。第 i 行有 n 个整数 wi1,wi2,…,win(0≤wij≤1 000 000 000),表示地图第 i
行格子的高度。
【输出】
输出一行两个整数,分别表示山峰和山谷的数量。
【输入样例】
5
8 8 8 7 7
7 7 8 8 7
7 7 7 7 7
7 8 8 7 8
7 8 8 8 8
【输出样例】
2 1
样例输入2:
5
5 7 8 3 1
5 5 7 6 6
6 6 6 2 8
5 7 2 5 8
7 1 0 1 7
样例输出2:
3 3
用两个标记,记录连通块周围是否有比当前连通块高的或矮的
#include<bits/stdc++.h>
using namespace std; using ll = long long;
int dir[8][2] = { 1, 0, -1, 0, 0, 1, 0, -1, 1, -1, 1, 1, -1, -1, -1, 1 };
//using lll = __int128; template <class T> istream& read(T& x, istream& cin = std::cin) { T num = 0; bool f = 0; char ch = 0; while (!isdigit(ch)) { f |= ch == '-'; if (!cin.get(ch)) return cin; }while (isdigit(ch)) { num = (num << 3) + (num << 1) + (ch ^ 48); if (!cin.get(ch)) break; }x = f ? -num : num; return cin; }template <class T> ostream& write(T x, ostream& cout = std::cout) { if (x < 0) cout.put('-'), x = -x; if (x > 9) write(x / 10); cout.put(x % 10 + '0'); return cout; }ostream& operator<<(ostream& cout, lll x) { write(x); return cout; }istream& operator>>(istream& cin, lll& x) { return read(x); }bool check(int i, int j);
bool check(int i, int j);
const int N = 1e3 + 10, mod = 1e9 + 7, INF = 0x3f3f3f3f;
int n, m, g[N][N];
int cnt_down, cnt_up;
void init() {
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> g[i][j];
}
}
return;
}
bool st[N][N];
using pii = pair<int, int>;
void bfs(int sx, int sy) {
queue<pii> qu;
qu.emplace(sx, sy);
st[sx][sy] = 1;
bool f1 = 0, f2 = 0; // f2周围有比当前高度高的,f1周围有比当前高度低的
while (qu.size()) {
auto [x, y] = qu.front();
qu.pop();
for (int i = 0; i < 8; i++) {
int nx = x + dir[i][0], ny = y + dir[i][1];
if (!nx || !ny || nx > n || ny > n) continue;
if (g[nx][ny] < g[x][y]) f1 = 1;
else if (g[nx][ny] > g[x][y]) f2 = 1;
if (g[x][y] != g[nx][ny] || st[nx][ny]) continue;
st[nx][ny] = true;
qu.emplace(nx, ny);
}
}
if (f1 && f2) return;
if (f1) cnt_up++;
else if (f2) cnt_down++;
else cnt_up++, cnt_down++;
}
void solve() {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (st[i][j]) continue;
bfs(i, j);
}
}
cout << cnt_up << " " << cnt_down << endl;
return;
}
int main(void) {
ios::sync_with_stdio(0); cin.tie(0); cout << setprecision(6) << fixed;
int TT = 1;
//cin >> TT;
for (int ii = 1; ii <= TT; init(), solve(), ii++, cout << "\n") {}
return 0;
}