正经题解|拯救olbh总部
2024-03-22 11:19:22
发布于:浙江
104阅读
0回复
0点赞
【算法分析】
可以在外面增加一圈 ,然后从 位置开始广搜所有 的位置,剩下没有被标记且为 的位置的个数就是答案。
【参考代码】
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e3 + 9;
char MAP[maxn][maxn];
bool vis[maxn][maxn];
struct node {
int x, y;
}l, r;
int n, m;
int dir[4][2] = { -1,0,0,1,1,0,0,-1 };
void bfs(int x, int y) {
queue<node> q;
q.push({ x,y });
vis[x][y] = 1;
while (q.size()) {
r = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
l.x = r.x + dir[i][0], l.y = r.y + dir[i][1];
if (l.x >= 0 && l.x <= n + 1 && l.y >= 0 && l.y <= m + 1 && !vis[l.x][l.y] && MAP[l.x][l.y] == '0') {
vis[l.x][l.y] = 1;
q.push(l);
}
}
}
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> MAP[i] + 1;
}
for (int i = 0; i <= n + 1; i++) {
for (int j = 0; j <= m + 1; j++) {
if (i == 0 || j == 0 || i == n + 1 || j == m + 1) MAP[i][j] = '0';
}
}
bfs(0, 0);
int ans = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (MAP[i][j] == '0' && !vis[i][j]) ans++;
}
}
cout << ans;
return 0;
}
【时间复杂度】
【预计得分】
这里空空如也
有帮助,赞一个