hdu - 1241 - Oil Deposits

本文提供了一种使用深度优先搜索(DFS)解决HDU 1241问题的方法,该问题涉及在一个由@和*组成的m*n地图上计算@形成的连续区域数量。代码使用C++实现,通过八个方向遍历每个@来查找相连的@块。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:一个m*n的地图,其中的格子要么是*,要么是@,对于@,横、竖、斜连着的成为一个块,问总共有多个@块。

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

——>>重刷寒假简单搜索题,还是不会用scanf或者getchar输入,失败。

#include <cstdio>
#include <iostream>
#include <cstring>

using namespace std;

const int maxn = 100 + 10;
char MAP[maxn][maxn];
int cnt, m, n;
int dx[] = {-1, -1, -1, 0, 1, 1,  1,  0};
int dy[] = {-1,  0,  1, 1, 1, 0, -1, -1};
bool vis[maxn][maxn];

void dfs(int x, int y)
{
    vis[x][y] = 1;
    for(int i = 0; i < 8; i++)
    {
        int newx = x + dx[i];
        int newy = y + dy[i];
        if(newx >= 0 && newx < m && newy >= 0 && newy < n && MAP[newx][newy] == '@' && !vis[newx][newy])
            dfs(newx, newy);
    }
}

int main()
{
    int i, j;
    while(scanf("%d%d", &m, &n) == 2 && m)
    {
        for(i = 0; i < m; i++)
            for(j = 0; j < n; j++)
                cin>>MAP[i][j];

        cnt = 0;
        memset(vis, 0, sizeof(vis));
        for(i = 0; i < m; i++)
            for(j = 0; j < n; j++)
            {
                if(MAP[i][j] == '@' && !vis[i][j])
                {
                    cnt++;
                    dfs(i, j);
                }
            }
        printf("%d\n", cnt);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值