山峰與山谷【BFS】
阿新 • • 發佈:2021-01-23
技術標籤:DFS;BFS
>Link
ybtoj山峰與山谷
>解題思路
BFS總體思路:對於每一個沒有搜到過的點進行bfs,把遇到的四周相同高度的點加入佇列,遇到不同的,用兩個變數記錄周圍高的和低的的個數。最後如果周圍沒有高的,說明此區域是山峰,如果周圍沒有低的,說明是山谷,否則什麼也不是(這樣子處理更加方便)
這裡有一個小細節(又是zzl巨爺幫我改的),如果搜尋過的在後面的bfs中就不用加入佇列的,不然會tle
>程式碼
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define N 2010
using namespace std;
const int xx[8] = {-1, -1, -1, 0, 0, 1, 1, 1}, yy[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
int n, a[N][N], head, tail, qx[N * N], qy[N * N], ans[5];
bool v[N][N], mark[N][N];
void bfs (int x, int y)
{
mark[x][y] = 1;
head = 0, tail = 1;
qx[1] = x, qy[1] = y, v[x][y] = 1;
int maxn = 0, minn = 0;
while (head < tail)
{
head++;
int ux = qx[head], uy = qy[head];
for (int i = 0; i < 8; i++)
{
int tx = ux + xx[i], ty = uy + yy[i];
if (tx < 1 || ty < 1 || tx > n || ty > n)
continue;
if (a[ux][uy] == a[tx][ty])
{
if (!mark[tx][ty])
{
mark[tx][ty] = 1;
tail++; qx[tail] = tx, qy[tail] = ty;
}
}
else
{
if (a[tx][ty] > a[ux][uy]) maxn++;
else minn++;
}
}
}
if (!maxn) ans[1]++;
if (!minn) ans[2]++;
}
int main()
{
scanf ("%d", &n);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) scanf ("%d", &a[i][j]);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
if (!mark[i][j]) bfs (i, j);
printf ("%d %d", ans[1], ans[2]);
return 0;
}