正经题解|拯救olbh总部
2024-03-22 11:19:22
发布于:浙江
200阅读
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;
}
【时间复杂度】
【预计得分】
全部评论 1
正经
1周前 来自 浙江
0#include<bits/stdc++.h> using namespace std; string mp[1005]; int n,m; bool vis[1005][1005]; struct Node{ int x,y; }; int dir[4][2]={0,1,1,0,0,-1,-1,0}; int main(){ cin>>n>>m; for(int i=1;i<=n;i++){ cin>>mp[i]; mp[i]='0'+mp[i]+'0'; } for(int i=0;i<=m+1;i++){ mp[0]+='0'; mp[n+1]+='0'; } queue<Node> q; q.push({0,0}); while(!q.empty()){ Node fr=q.front(); q.pop(); for(int i=0;i<4;i++){ int tx=fr.x+dir[i][0]; int ty=fr.y+dir[i][1]; if(tx>=0&&tx<=n+1&&ty>=0&&ty<=m+1&&mp[tx][ty]=='0'&&!vis[tx][ty]){ q.push({tx,ty}); vis[tx][ty]=true; } } } int cnt=0; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ if(mp[i][j]=='0'&&!vis[i][j])cnt++; } } cout<<cnt<<endl; return 0; }1周前 来自 浙江
0












有帮助,赞一个