山峰和山谷(搜索与图论、bfs)

【题目描述】
给定一个 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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值