dfs之找连通块

#寻找连通块

题目传送门

题目的大致意思就是给你一张地图,找到规定的字符所组成的连通块的数量。

Sample Input
1 1
*
3 5
*@*@*
**@**
*@*@*
1 8
@@****@*
5 5 
****@
*@@*@
*@**@
@@@*@
@@**@
0 0 
    
Sample Output
0
1
2
2

这个题,我们找由@组成的连通块的数量。这里的连通块的定义为以某点为中心,向周围八个点扩散的都是和中心点连通的点。
这仍然是个dfs的题,当然,也有bfs的解法。

#include<iostream>
#include<queue>
#include<string.h>
#include<string>
#include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=1e3+5;
int n,m,ans=0;
char mp[N][N];
int flag[N][N];//标记数组
int c[8][2]={{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}};//方向数组
void dfs(int x,int y)
{
    for(int i=0;i<8;i++)
    {
        int dx=x+c[i][0];
        int dy=y+c[i][1];
        if(mp[dx][dy]=='@'&&dx>=1&&dy>=1&&dx<=n&&dy<=m&&!flag[dx][dy])
        {
            flag[dx][dy]=1;//把连通的点都标记,下次就不会再走这里
            dfs(dx,dy);
        }

    }
}
int main()
{
    std::ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    while(cin>>n>>m)
    {
        if(n==0&&m==0)
            break;
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=m;j++)
            {
                cin>>mp[i][j];
            }
        }
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=m;j++)
            {
                if(!flag[i][j]&&mp[i][j]=='@')
                {
                    flag[i][j]=1;//标记这个点
                    ans++;//连通块的数量加一
                    dfs(i,j);//以这点为中心,向周围扩散,寻找连通块
                }
            }
        }
        cout<<ans<<endl;
        memset(flag,0,sizeof flag);
        ans=0;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值