[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 @ 2022-08-07 22:31  wKingYu  阅读(20)  评论(0编辑  收藏  举报