hdu 2952 Counting Sheep(dfs)

本文提供了一种解决HDU 2952迷宫问题的方法,通过深度优先搜索(DFS)算法来计算连通块的数量。使用C++实现,详细展示了如何遍历地图并标记已访问过的连通区域。

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2952

#include <cstdio>
#include <cstring>
int H,W;
char map[101][101];//地图
int book[101][101];//标记
int next[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};//方向

void dfs(int x,int y)
{
    int tx,ty,k;
    for(k = 0; k < 4; ++k)
    {
        tx = x + next[k][0];
        ty = y + next[k][1];
        if(tx < 1 || ty < 1 || tx > H || ty > W)//判断是否越界
            continue;
        if(map[tx][ty] == '#' && book[tx][ty] == 0)
        {
            book[tx][ty] = 1;
            dfs(tx,ty);
        }
    }
    return ;
}

int main()
{
    int T;
    int sum;
    int i,j;
    scanf("%d",&T);
    while(T--)
    {
        sum = 0;
        scanf(" %d %d",&H,&W);
        memset(book,0,sizeof(book));
        for(i = 1; i <= H; ++i)
            for(j = 1; j <= W; ++j)
                scanf(" %c",&map[i][j]);
        for(i = 1;i <= H; ++i)
            for(j = 1; j <= W; ++j)
                if(map[i][j] == '#' && book[i][j] == 0)
                {
                    sum++;
                    book[i][j] = 1;
                    dfs(i,j);
                }
        printf("%d\n",sum);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值