洛谷1451(BFS)

#include"bits/stdc++.h"
using namespace std;
int mp[110][110];
bool vis[110][110];
int dx[4]={1,-1,0,0},dy[4]={0,0,1,-1};
struct point
{
    int x,y;
};
int ans;
int n,m;
queue<point>q;
void bfs(int sx,int sy)
{ 
        point nw;
        nw.x=sx;
        nw.y=sy;
        vis[sx][sy]=true;
        q.push(nw);
        while(!q.empty())
        {
            point p=q.front();q.pop();
            for(int i=0;i<4;i++)
            {
                point t; 
                t.x=p.x+dx[i];
                t.y=p.y+dy[i];
                if(t.x<0||t.x>=n||t.y<0||t.y>=m||mp[t.x][t.y]==0)    continue;
                if(!vis[t.x][t.y])
                {
                    vis[t.x][t.y]=true;
                    q.push(t);
                }
            }
        }
}
int main()
{
    cin>>n>>m;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
            scanf("%1d",&mp[i][j]);
        
    }
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        if(mp[i][j]!=0&&!vis[i][j])
        {
            bfs(i,j);
            ans++;
        }
    }
    cout<<ans<<endl;
}

小白成长记

posted @   cxy8  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
点击右上角即可分享
微信分享提示