【Ybtoj 第5章 例题2】山峰和山谷【广搜】

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述


解题思路

首先要知道:
周围只有高的,就是山谷
周围只有矮的,就是山峰
有高有矮,谷、峰都不是
没高没矮是山谷也是山峰

好顺

我们每次从一个没搜过的点开始广搜,只把那些高度都相同的加进队列,对于高度不同的统计数量,搜完后如果大于起点高度的没有一个就是山峰,反之则是山谷。。(由于广搜具有单调性,所以只把高度都相同的加进队列,就可以刚好搜到周围包围的一圈)


代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;

string s;
const int dx[9]= {
    
    0,1,-1,0,0,1,-1,1,-1};
const int dy[9]= {
    
    0,0,0,1,-1,1,1,-1,-1};
int n,ans1,ans2,a[2000][2000],v[2000][2000],dis[2000000],st[2000000][3],h,t;

bool check(int x,int y)
{
    
    
    if(x>0&&x<=n&&y>0&&y<=n)
        return 1;
    else return 0;
}
int bfs(int x,int y)
{
    
    
    int h=0,t=1,minn=0,maxn=0;
    v[x][y]=1;
    st[1][1]=x;
    st[1][2]=y;
    while(h<t) {
    
    
        h++;
        
        for(int i=1; i<=8; i++) {
    
    
			int xx=st[h][1]+dx[i],yy=st[h][2]+dy[i];
            if(check(xx,yy)) {
    
    
                if(a[xx][yy]==a[x][y]) {
    
    
                    if(v[xx][yy]==0) {
    
    
                        t++;
                        st[t][1]=xx;
                        st[t][2]=yy;
                        v[xx][yy]=1;
                    }
                }
				else
				{
    
    
					if(a[x][y]>a[xx][yy])minn++;
					if(a[x][y]<a[xx][yy])maxn++;
				}
            }
        }
    }
    if(minn==0)ans2++;
    if(maxn==0)ans1++;
}


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(!v[i][j])
                bfs(i,j);
        }
    }
	printf("%d %d",ans1,ans2);
}


猜你喜欢

转载自blog.csdn.net/kejin2019/article/details/112393257