思路:BFS
一道水题,其实就是对于flood fill的一种变形,我们直接用BFS就解决了,标志在围墙之外的0的状态,然后统计没有被遍历的0就行了。
上代码:
#include<iostream>
#include<stdio.h>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<algorithm>
#include<stack>
#include<queue>
#include <iomanip>
#include<sstream>
#include<numeric>
#include<map>
#include<limits.h>
#include<set>
#define int long long
#define MAX 1010
#define _for(i,a,b) for(int i=a;i<(b);i++)
#define ALL(x) x.begin(),x.end()
using namespace std;
typedef pair<int, int> PII;
int n, m;
int counts=INT_MAX;
int a, b;
int dx[] = { -1,1,0,0 };
int dy[] = { 0,0,-1,1 };
queue<PII>q;
int res = 0;
char maps[MAX][MAX];
int st[MAX][MAX];
void bfs(int x, int y) {
q.push({ x,y });
st[x][y] = 1;
while (!q.empty()) {
auto tmp = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int a = tmp.first + dx[i];
int b = tmp.second + dy[i];
if (st[a][b])
continue;
if (maps[a][b] == '*')
continue;
if (a<0 || a > n + 1 || b<0 || b>m + 1)
continue;
st[a][b] = 1;
q.push({ a,b });
}
}
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> maps[i][j];
}
}
bfs(0, 0);
_for(i, 1, n + 1) {
_for(j, 1, m + 1) {
if (maps[i][j] == '0' && !st[i][j])
res++;
}
}
cout << res;
return 0;
}