题目相当于要求统计所有不与在边界的 连通的 的数量,从所有位于边界位置的 开始 后标记即可。

#include <bits/stdc++.h>
using namespace std;
const int X4[4] = {1, -1, 0, 0}, Y4[4] = {0, 0, 1, -1};



void solve(){
    int n, m;
    cin >> n >> m;
    vector<string> mp(n + 5);
    for (int i = 1; i <= n; i++) {
        cin >> mp[i];
        mp[i] = "#" + mp[i];
    }
    vector<vector<int>> vis(n + 5, vector<int>(m + 5));
    auto dfs = [&](auto dfs, int x, int y) -> void {
        vis[x][y] = 1;
        for (int i = 0; i < 4; i++) {
            int xx = x + X4[i], yy = y + Y4[i];
            if (xx < 1 || n < xx || yy < 1 || m < yy) continue;
            if (vis[xx][yy]) continue;
            if (mp[xx][yy] == '*') continue;
            dfs(dfs, xx, yy);
        }
    };
    for (int i = 1; i <= m; i++) {
        if (mp[1][i] == '0' && !vis[1][i]) dfs(dfs, 1, i);
        if (mp[n][i] == '0' && !vis[n][i]) dfs(dfs, n, i);
    }
    for (int i = 1; i <= n; i++) {
        if (mp[i][1] == '0' && !vis[i][1]) dfs(dfs, i, 1);
        if (mp[i][m] == '0' && !vis[i][m]) dfs(dfs, i, m);
    }
    int ans = 0;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            if (!vis[i][j] && mp[i][j] == '0') ans++;
        }
    }
    cout << ans;
}

signed main(){
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    int _T = 1;
    // cin >> _T;
    while (_T--){ 
        solve();
    }
    return 0;
}