小X学游泳

Problem Detail - 【提高】小X学游泳 - 追梦算法网

也就是上下左右同一个数字的为一个连通块,看看最大的连通块有多大

其实也就是flood fill问题啦

dfs:

#include<iostream>
using namespace std;
int n,m;
const int N=1010;
char ch[N][N];
bool st[N][N];
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
int sum;
int dfs(int x,int y)
{
    st[x][y]=true;
    sum++;
    for(int i=0;i<4;i++)
    {
        int xx=x+dx[i],yy=y+dy[i];
        if(xx>=0&&yy>=0&&xx<n&&yy<m&&ch[xx][yy]==ch[x][y]&&!st[xx][yy])
            dfs(xx,yy);
    }
    return sum;
}
int main(){
    cin>>n>>m;
    for(int i=0;i<n;i++)
        for(int j=0;j<m;j++)
            cin>>ch[i][j];
    int maxn=-1;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(!st[i][j])
            {
                sum=0;
                int t=dfs(i,j);
                maxn=max(maxn,t);
            }
        }
    }
    cout<<maxn;
    return 0;
}

bfs:

#include<iostream>
#include<queue>
using namespace std;
typedef pair<int,int> PAII;
int n,m,sum;
const int N=1010;
char ch[N][N];
bool st[N][N];
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
int bfs(int x,int y)
{
    sum++;
    queue<PAII> q;
    st[x][y]=true;
    q.push({x,y});
    while(q.size())
    {
        auto t=q.front();
        q.pop();
        int a=t.first,b=t.second;
        for(int i=0;i<4;i++)
        {
            int xx=a+dx[i],yy=b+dy[i];
            if(xx>=0&&yy>=0&&xx<n&&yy<m&&ch[xx][yy]==ch[x][y]&&!st[xx][yy])
            {
                sum++;
                q.push({xx,yy});
                st[xx][yy]=true;
            }
        }
    }
    return sum;
}
int main(){
    cin>>n>>m;
    for(int i=0;i<n;i++)
        for(int j=0;j<m;j++)
            cin>>ch[i][j];
    int maxn=-1;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(!st[i][j])
            {
                sum=0;
                int t=bfs(i,j);
                maxn=max(maxn,t);
            }
        }
    }
    cout<<maxn;
    return 0;
}

 

posted @ 2022-04-12 22:44  小志61314  阅读(687)  评论(0)    收藏  举报