2521. Guarding the Farm

单点时限: 2.0 sec

内存限制: 256 MB

The farm has many hills upon which Farmer John would like to place guards to ensure the safety of his valuable milk-cows.

He wonders how many guards he will need if he wishes to put one on top of each hill. He has a map supplied as a matrix of integers; the matrix has N (1<=N<=700) rows and M(1<=M<=700) columns. Each member of the matrix is an altitude H(0<=H<=10000).

Help him determine the number of hilltops on the map.

A hilltop is one or more adjacent matrix elements of the same value surrounded xclusively by either the edge of the map or elements with a lower (smaller) altitude. Two different elements are adjacent if the magnitude of difference in their coordinates is no greater than and the magnitude of differences in their coordinates is also no greater than .

输入格式
Line 1: Two space-separated integers: and
Lines 2…: Line describes row of the matrix with space-separated integers:
输出格式
Line 1: A single integer that specifies the number of hilltops
样例
input
8 7
4 3 2 2 1 0 1
3 3 3 2 1 0 1
2 2 2 2 1 0 0
2 1 1 1 1 0 0
1 1 0 0 0 1 0
0 0 0 1 1 1 0
0 1 2 2 1 1 0
0 1 1 1 2 1 0
output
3
提示
OUTPUT DETAILS:

There are three peaks: The one with height 4 on the left top, one of the points with height 2 at the bottom part, and one of the points with height 1 on the right top corner.

/*
思路:bfs/dfs+贪心
*/
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<queue>
#include<algorithm>
#define Pair pair<int,int>
#define N 1100
using namespace std;
bool vis[N][N];
int n,m,x,y,h[N][N],ans,sum;
int xx[8]= {0,0,-1,-1,-1,1,1,1};
int yy[8]= {1,-1,1,0,-1,1,0,-1};
struct Node {
	int x,y,h;
} node[N*N];
int cmp(Node a,Node b) {
	return a.h>b.h;
}
void dfs(int x,int y) {
	for(int i=0; i<8; i++) {
		int fx=x+xx[i],fy=y+yy[i];
		if(fx<1||fy<1||fx>n||fy>m) continue;
		if(h[fx][fy]<=h[x][y]&&!vis[fx][fy]) {
			vis[fx][fy]=true;
			dfs(fx,fy);
		}
	}
	return ;
}
void bfs(int x,int y) {
	Pair p(x,y);
	queue<Pair>q;
	q.push(p);
	while(!q.empty()) {
		Pair f=q.front();
		q.pop();
		for(int i=0; i<8; i++) {
			int fx=f.first+xx[i];
			int fy=f.second+yy[i];
			if(fx<1||fy<1||fx>n||fy>m) continue;
			if(h[fx][fy]<=h[f.first][f.second]&&!vis[fx][fy]) {
				vis[fx][fy]=true;
				Pair t(fx,fy);
				q.push(t);
			}
		}
	}
}
int main() {
	cin>>n>>m;
	for(int i=1; i<=n; i++)
		for(int j=1; j<=m; j++) {
			cin>>h[i][j];
			node[++sum].x=i;
			node[sum].y=j;
			node[sum].h=h[i][j];
		}
	sort(node+1,node+1+sum,cmp);
	for(int i=1; i<=sum; i++) {
		x=node[i].x,y=node[i].y;
		if(vis[x][y]) continue;
		vis[x][y]=true;
		ans++;
		bfs(x,y);
		//	dfs(x,y);
	}
	printf("%d",ans);
	return  0;
}

猜你喜欢

转载自blog.csdn.net/qq_40394960/article/details/105959635