AcWing 1113. 红与黑 解题思路及代码

先贴个题目:

以及原题链接: 1113. 红与黑 - AcWing题库icon-default.png?t=N7T8https://www.acwing.com/problem/content/1115/

这题也算是裸的模板题,算法是Flood Fill。可以用dfs和bfs做。

代码如下:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
#define x first
#define y second

const int N = 30;

int w, h;
char map[N][N];
int dx[4] = {0, 0, -1, 1}, dy[4] = {-1, 1, 0, 0};
bool sign[N][N];

int bfs(PII start)
{
    queue<PII> q;
    int ans = 1;
    sign[start.x][start.y] = true;
    q.push(start);
    while (q.size())
    {
        PII tmp = q.front();
        q.pop();
        for (int i = 0; i < 4; ++i)
        {
            int tx = tmp.x + dx[i], ty = tmp.y + dy[i];
            if (tx < 0 || tx >= h || ty < 0 || ty >= w)
                continue;
            if (map[tx][ty] == '.' && !sign[tx][ty])
            {
                ans++;
                sign[tx][ty] = true;
                q.push(make_pair(tx, ty));
            }
        }
    }
    return ans;
}

int main()
{
    while (1)
    {
        cin >> w >> h;
        if(w==0&&h==0)
            break;
        memset(sign, false, sizeof(sign));
        PII start;
        for (int i = 0; i < h; ++i)
        {
            getchar();
            scanf("%s", &map[i]);
        }
        for (int i = 0; i < h; ++i)
        {
            for (int j = 0; j < w; ++j)
            {
                if (map[i][j] == '@')
                    start = make_pair(i, j);
            }
        }
        cout << bfs(start)<<endl;
    }

    return 0;
}

我因为后面有dfs和bfs都写的,所以这题只写了bfs版本(懒)

by————2024.4.6刷题记录

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值