搜索
您的当前位置:首页正文

【刷题】搜索——BFS:山峰和山谷

来源:独旅网


Flood Fill算法,bfs遍历一遍,对于连通块的每个格子,都判断是否满足山峰山谷的条件,不满足则该连通块不是山峰或山谷

#include <iostream>
#define x first
#define y second
using namespace std;

typedef pair<int, int> PII;

int n, w[1005][1005];
bool st[1005][1005];
PII q[1000005];
PII bfs(int a, int b) {
	int is_peak = 1, is_valley = 1;
	
	int head = 0, tail = 0;
	st[a][b] = true;
	q[head] = {a, b};
	while(head <= tail) {
		PII t = q[head ++ ];
		
		for (int i = -1; i <= 1; i ++ ) {
			for (int j = -1; j <= 1; j ++ ) {
				int sx = t.x + i;
				int sy = t.y + j;
				if (sx < 0 || sx >= n || sy < 0 || sy >= n) continue;
				
				if (w[sx][sy] > w[t.x][t.y]) is_peak = 0;
				if (w[sx][sy] < w[t.x][t.y]) is_valley = 0;
				
				if (st[sx][sy] || w[sx][sy] != w[t.x][t.y]) continue;
				
				q[ ++ tail] = {sx, sy};
				st[sx][sy] = true;
			}
		}
	}
	return {is_peak, is_valley};
}

int main() {
	scanf("%d", &n);
	for (int i = 0; i < n; i ++ ) {
		for (int j = 0; j < n; j ++ )
			scanf("%d", &w[i][j]);
	}
	int ans_peak = 0, ans_valley = 0;
	for (int i = 0; i < n; i ++ ) {
		for (int j = 0; j < n; j ++ ) {
			if (!st[i][j]) {
				PII cnt = bfs(i, j);
				ans_peak += cnt.x;
				ans_valley += cnt.y;
			}
		}
	}
	printf("%d %d\n", ans_peak, ans_valley);
	return 0;
} 

因篇幅问题不能全部显示,请点此查看更多更全内容

Top