• sdf1552



    问题 B: 细胞问题

    时间限制: 1 Sec  内存限制: 128 MB
    提交: 739  解决: 402
    [提交][状态][讨论版]

    题目描述

    一矩形阵列由数字0到9组成,数字1到9代表细胞,细胞的定义为沿细胞数字上下左右还是细胞数字则为同一细胞,求给定矩形阵列的细胞个数。
    如:阵列
    0234500067
    1034560500
    2045600671
    0000000089  
    有4个细胞

    输入

    第一行 :两个数字M N (1<=M<=50 1<=N<80)表示该阵列有M行N列,从第2行到第M+1行 每行有连续的N个字符。

    输出

    一行: 细胞个数。

    样例输入

    4 10
    0234500067
    1034560500
    2045600671
    0000000089
    

    样例输出

    4

    提示


    #include<cstdio>

    #include<cstring>
    #include<iostream>
    #include<string>
    #include<algorithm>
    #include<queue>
    using namespace std;

    /*
    4 10
    0234500067
    1034560500
    2045600671
    0000000089
    思路,
    */

    int m,n;
    const int MAXM=50;
    const int MAXN=80;
    int a[MAXM][MAXN];//存地图
    int vis[MAXM][MAXN];//存标记
    int dir[4][2] = {
        { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 }
    };

    void bfs(int i, int j)
    {
        queue<pair<int,int>> q;
        //找到一个队列头
        vis[i][j]=1;
        q.push({i, j});

        //所有相关的全部入队搜索
        while(!q.empty())
        {
            auto f=q.front();
            q.pop();
            int nx,ny;
            for(int k=0;k<4;k++)
            {
                nx=f.first+dir[k][0];
                ny=f.second+dir[k][1];
                if(nx<0 || nx>=m || ny<0 || ny>=n)
                    continue;
                if(a[nx][ny]!=0 && !vis[nx][ny])
                {
                    vis[nx][ny]=1;
                    q.push({nx, ny});
                }
            }
        }
    }

    int main()
    {  
        cin>>m>>n;
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
            {
                char c;
                cin>>c;
                a[i][j]=c-'0';
            }

        int cnt=0;//总共几个细胞

        // 遍历所有非0点,用队列宽搜,搜索时做标记
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
            {
                //找到一个队列头
                if(a[i][j]!=0 && !vis[i][j])
                {
                    cnt++;
                    bfs(i,j);
                }

            }
        cout<<cnt<<endl;
        return 0;
    }



  • 相关阅读:
    (Relax njuptoj)1009 数的计算(DP)
    Eclipse使用技巧总结(二)
    Ibatis的分页机制的缺陷
    TFT ST7735的Netduino驱动
    超级求爱程序--为我们的程序工作找乐子
    Selenium Grid跨浏览器-兼容性测试
    PHP一般情况下生成的缩略图都比较不理想
    库目录和头文件目录中生成画图函数
    根据PHP手册什么叫作变量的变量?
    数据库的最基本的逻辑结构组成架构
  • 原文地址:https://www.cnblogs.com/cute/p/15424671.html
Copyright © 2020-2023  润新知