【POI 2007】 山峰和山谷

【题目链接】

            https://www.lydsy.com/JudgeOnline/problem.php?id=1102

【算法】

           广度优先搜索

【代码】

         

#include<bits/stdc++.h>
using namespace std;
#define MAXN 1010
const int INF = 2e9;
const int dx[8] = {0,0,-1,1,-1,-1,1,1};
const int dy[8] = {-1,1,0,0,-1,1,-1,1};

int i,j,n,mn,mx,ans1,ans2;
int a[MAXN][MAXN];
bool visited[MAXN][MAXN];

inline bool valid(int x,int y)
{
        return x >= 1 && x <= n && y >= 1 && y <= n;
}
inline void bfs(int x,int y)
{
        int i,tx,ty;
        queue< pair<int,int> > q;
        pair<int,int> cur;
        while (!q.empty()) q.pop();
        q.push(make_pair(x,y));
        while (!q.empty())
        {
                cur = q.front();
                q.pop();
                for (i = 0; i < 8; i++)
                {
                        tx = cur.first + dx[i];
                        ty = cur.second + dy[i];
                        if (valid(tx,ty))
                        {
                                if (a[cur.first][cur.second] == a[tx][ty] && !visited[tx][ty])
                                {
                                        q.push(make_pair(tx,ty));
                                        visited[tx][ty] = true;
                                } else 
                                {
                                        mn = min(mn,a[tx][ty]);
                                        mx = max(mx,a[tx][ty]);
                                }
                        }
                }        
        }        
}

int main() 
{
        
        scanf("%d",&n);
        for (i = 1; i <= n; i++)
        {
                for (j = 1; j <= n; j++)
                {
                        scanf("%d",&a[i][j]);
                }
        }
        for (i = 1; i <= n; i++)
        {
                for (j = 1; j <= n; j++)
                {
                        if (!visited[i][j])
                        {
                                mx = mn = a[i][j];
                                visited[i][j] = true;
                                bfs(i,j);
                                if (mx <= a[i][j] && mn <= a[i][j]) ans1++;
                                if (mx >= a[i][j] && mn >= a[i][j]) ans2++;
                        }
                }
        }
        printf("%d %d\n",ans1,ans2);
        
        return 0;
    
}

猜你喜欢

转载自www.cnblogs.com/evenbao/p/9274980.html