[AcWing 1113] 红与黑

image
image

Flood Fill 的 DFS 写法


点击查看代码
#include<bits/stdc++.h>

using namespace std;

typedef long long LL;

const int N = 100 + 10;

int n, m;
char g[N][N];
bool st[N][N];
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};

int dfs(int x, int y)
{
    st[x][y] = true;
    int cnt = 1;
    for (int i = 0; i < 4; i ++) {
        int a = x + dx[i], b = y + dy[i];
        if (a < 0 || a >= n || b < 0 || b >= m || st[a][b] || g[a][b] == '#')
            continue;
        cnt += dfs(a, b);
    }
    return cnt;
}

void solve()
{
    while (cin >> m >> n) {
        if (n == 0 && m == 0)
            break;
        int x = 0, y = 0;
        memset(st, false, sizeof st);
        for (int i = 0; i < n; i ++)
            for (int j = 0; j < m; j ++) {
                cin >> g[i][j];
                if (g[i][j] == '@') {
                    x = i;
                    y = j;
                }
            }
        cout << dfs(x, y) << endl;
    }
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    solve();

    return 0;
}

  1. DFS + 布尔数组避免重复搜索
posted @   wKingYu  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
欢迎阅读『[AcWing 1113] 红与黑』
点击右上角即可分享
微信分享提示