https://ac.nowcoder.com/acm/problem/20898
两个条件
#include <bits/stdc++.h> using namespace std; const int maxn = 1e6 + 10; int n,m; vector<char> a[maxn]; int ans; int t,flag; int dp[4][2] = {{0,1},{0,-1},{-1,0},{1,0}}; void dfs(int x,int y){ t++; a[x][y] = '@'; for(int i = 0; i < 4; i++) { int dx = x + dp[i][0],dy = y + dp[i][1]; if (dx < 0 || dx >= n || dy < 0 || dy >= m){ flag = 1; continue; } if(a[dx][dy] == '.') dfs(dx,dy); } } int main(){ // freopen("in","r",stdin); ios::sync_with_stdio(0); cin >> n >> m; char c; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++) { cin >> c; a[i].push_back(c); } } for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(a[i][j] == '#') ans++; else if(a[i][j] == '.'){ flag = 0; t = 0; dfs(i,j); if(!flag){ ans += t; } } } } cout << ans << endl; return 0; }