题目描述
FGD小朋友特别喜欢爬山,在爬山的时候他就在研究山峰和山谷。
为了能够对旅程有一个安排,他想知道山峰和山谷的数量。
给定一个地图,为FGD想要旅行的区域,地图被分为 n×n 的网格,每个格子 (i,j) 的高度 w(i,j) 是给定的。
若两个格子有公共顶点,那么它们就是相邻的格子,如与 (i,j) 相邻的格子有(i−1,j−1),(i−1,j),(i−1,j+1),(i,j−1),(i,j+1),(i+1,j−1),(i+1,j),(i+1,j+1)。
我们定义一个格子的集合 S 为山峰(山谷)当且仅当:
- S 的所有格子都有相同的高度。
- S 的所有格子都连通。
- 对于 s 属于 S,与 s 相邻的 s′ 不属于 S,都有 ws>ws′(山峰),或者 ws
题目代码
#include
#include
#define x first
#define y second
using namespace std;
typedef pair PII;
const int N = 1010, M = N * N;
int n;
int h[N][N];
PII q[M];
bool st[N][N];
void bfs(int sx, int sy, bool & has_higher, bool & has_lower)
{
int hh = 0, tt = 0;
q[0] = {sx, sy};
st[sx][sy] = true;
while(hh = 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_higher = true; // 相邻有比它高的
else has_lower = true; // 相邻有比它低的
}
else if(!st[i][j]) // 在同一连通块内
{
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;
}
Original: https://www.cnblogs.com/esico/p/16467091.html
Author: esico
Title: AcWing 1106. 山峰和山谷(搜索)
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/619887/
转载文章受原作者版权保护。转载请注明原作者出处!