【Ybtoj Chapter 5 Example 2】Mountains and valleys【Wide Search】

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here


Problem solving ideas

The first thing to know is that there
are only high surroundings, that is, valleys,
and only low surroundings, that is, peaks.
There are high and low, and there are neither valleys nor peaks. If there is
no high or low, there are valleys and peaks.

So smooth

Every time we start a wide search from a point that has not been searched, only those with the same height are added to the queue. For statistical numbers with different heights, after the search, if the height is greater than the starting height, none of them is a mountain, otherwise it is a valley. . (Because of the monotonic nature of the wide search, just add the same height to the queue, you can just search the surrounding circle)


Code

#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);
}


Guess you like

Origin blog.csdn.net/kejin2019/article/details/112393257