bfs 最大平台

题目描述

下面是一个4×4的矩阵,它的特点是:(1)矩阵的元素都是正整数;(2)数值相等的元素相邻。这样,这个矩阵就形成了一级级“平台”,其最大的“平台”面积为8,高度(元素值)为6。若有一个 N×N的矩阵也具有上面矩阵的特点,求矩阵最大“平台”的面积和高度。
6 6 6 7
1 6 3 7
1 6 6 7
6 6 7 7

输入

第一行为N(1≤N≤100),以下为N×N的矩阵。

输出

第一行为平台的最大面积;
第二行为元素值。

样例输入

4
6 6 6 7
1 6 3 7
1 6 6 7
6 6 7 7

样例输出

8
6


#include <iostream>

using namespace std;

int Map[105][105];
int tempS,tempN;
int dx[4] = {0,0,1,-1};
int dy[4] = {1,-1,0,0};
int n;
void bfs(int x,int y)
{
    for(int i=0;i<4;i++)
    {
        int nowx = x+dx[i],nowy = y+dy[i];
        if(nowx>=0&&nowx<n&&nowy>=0&&nowy<n&&Map[nowx][nowy]==tempN)
        {
            tempS++;
            Map[nowx][nowy] = 0;
            bfs(nowx,nowy);
        }
    }
}
int main()
{

    cin>>n;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            cin>>Map[i][j];
        }
    }
    int AnsS = 0,AnsN = 0;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            if(Map[i][j]!=0)
            {
                tempS = 1;
                tempN = Map[i][j];
                Map[i][j] = 0;
                bfs(i,j);
            }
            if(tempS>AnsS)
            {
                AnsS = tempS;
                AnsN = tempN;
            }
        }
    }
    cout<<AnsS<<endl<<AnsN;
}

猜你喜欢

转载自www.cnblogs.com/hao-tian/p/9368118.html
BFS