eoj2521

Guarding the Farm

Time Limit:2000MSMemory Limit:65536KB
Total Submit:124Accepted:48

Description

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_ij (0 <= H_ij <= 10,000).
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 X coordinates is no greater than 1 and the magnitude of differences in their Y coordinates is also no greater than 1.

Input

* Line 1: Two space-separated integers: N and M

* Lines 2..N+1: Line i+1 describes row i of the matrix with M
space-separated integers: H_ij

Output

* Line 1: A single integer that specifies the number of hilltops

Sample 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

Sample 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.

题目:EOJ2521

 

题目分析:

对每个点进行dfs,向八个方向传递,若四周有比该点大的值返回FALSE,若相等返回flag&下一层dfs,否则返回TRUE,把访问过的标记为已访问。遍历每一个没有被访问过的点,dfs该点,若返回true则计数器+1。

 

AC代码:

#include <iostream>

#include <cstdio>

#include <cstring>

 

using namespace std;

int map[702][702];

bool visited[702][702];

intdx[]={-1,-1,0,1,1,1,0,-1},dy[]={0,1,1,1,0,-1,-1,-1};

 

bool bfs(int x,int y,int n,int m){

   visited[x][y]=true;

   bool flag=true;

   for(int i=0;i<8;++i){

       int xx=x+dx[i],yy=y+dy[i];

       if(xx>=0 && xx<n && yy>=0 && yy<m){

           if(map[xx][yy]==map[x][y] && !visited[xx][yy])

                flag&=bfs(xx,yy,n,m);

           else if(map[xx][yy]>map[x][y])

                flag=false;

       }

    }

   return flag;

}

 

int main()

{

   int n,m,i,j;

   while(~scanf("%d%d",&n,&m)){

       for(i=0;i<n;++i)

           for(j=0;j<m;++j)

               scanf("%d",&map[i][j]);

       memset(visited,false,sizeof(visited));

       int ans=0;

       for(i=0;i<n;++i){

           for(j=0;j<m;++j){

                if(!visited[i][j])

                    if(bfs(i,j,n,m)){

                        ++ans;

                    }

           }

       }

       cout<<ans<<endl;

    }

   return 0;

}

 



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值