【题目描述】
https://www.acwing.com/problem/content/description/1108/
https://szkopul.edu.pl/problemset/problem/rd6H05Dm8ME79sO3U9_f_ga_/site/?key=statement
左上图:2个山峰,1个山谷 右上图:3个山峰,3个山谷
【算法代码】
#include <bits/stdc++.h>
using namespace std;
//typedef pair<int,int> PII;
struct PII{
int u;
int v;
}po;
const int maxn=1010;
int g[maxn][maxn];
bool f[maxn][maxn];
int n;
void bfs(int x,int y,bool& higher,bool& lower) {
queue<PII> q;
//q.push({x,y});
po.u=x;
po.v=y;
q.push(po);
while (q.size()) {
PII t=q.front();
q.pop();
f[t.u][t.v]=true;
//direction
int dx[]= {-1,-1,-1,0,0,1,1,1};
int dy[]= {-1,0,1,-1,1,-1,0,1};
for(int i=0; i<8; i++) {
int a=t.u+dx[i],b=t.v+dy[i];
if(a>=0 && a<n && b>=0 && b<n) {
if(g[t.u][t.v]<g[a][b]) higher=true;
else if(g[t.u][t.v]>g[a][b]) lower=true;
else if(g[t.u][t.v]==g[a][b] && f[a][b]==false) {
f[a][b]=true;
po.u=a;
po.v=b;
q.push(po);
}
}
}
}
}
int main() {
cin>>n;
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
cin>>g[i][j];
int peak=0,valley=0;
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
if(!f[i][j]) {
bool has_higher=false,has_lower=false;
bfs(i,j,has_higher,has_lower);
if(!has_higher) peak++;
if(!has_lower) valley++;
}
cout<<peak<<" "<<valley;
return 0;
}
/*
in:
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
out:
2 1
in:
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
out:
3 3
*/
【参考文献】
https://blog.csdn.net/Miiiiiiiiiii/article/details/109587246
https://www.acwing.com/solution/content/6004/