大佬们帮帮忙
原题链接:8042.拯救oibh总部2024-12-17 20:53:39
发布于:广东
#include <bits/stdc++.h>
using namespace std;
int n, m;
const int max_n = 1100;
bool vis[max_n][max_n] = {false};
char mp[max_n][max_n];
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
struct node {
int x;
int y;
};
int bfs(int x, int y) {
queue<node> q;
q.push({x, y});
vis[x][y] = true;
int cnt = 0;
while (!q.empty()) {
node k = q.front();
q.pop();
cnt++;
for (int i = 0; i < 4; i++) {
int nx = k.x + dx[i];
int ny = k.y + dy[i];
if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && mp[nx][ny] == '0' &&!vis[nx][ny]) {
q.push({nx, ny});
vis[nx][ny] = true;
}
}
}
return cnt;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> mp[i][j];
}
}
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]) {
bool isd = true;
for (int k = 0; k < 4; k++) {
int nx = i + dx[k];
int ny = j + dy[k];
if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && mp[nx][ny]!= '*') { // 修正判断被包围的逻辑
isd = false;
break;
}
}
if (isd) {
Cnt += bfs(i, j);
}
}
}
}
cout <<Cnt << endl;
return 0;
}
全部评论 2
#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#include <iostream>
#include <queue>
using namespace std;
struct node{
int x,y;
};
queue<node> q;
char map[1005][1005];
int vis[1005][1005],dir[4][2]={1,0,0,1,-1,0,0,-1};
int n,m,ans=0;
void bfs(){
while(q.size()){
node t=q.front();
q.pop();
for(int i=0;i<4;i++){
int nx=t.x+dir[i][0];
int ny=t.y+dir[i][1];
if(nx<0 || nx>=n || ny<0 || ny>=m || vis[nx][ny] || map[nx][ny]'*'){
continue;
}
vis[nx][ny]=1;
q.push({nx,ny});
}
}
}
int main(){
cin>>n>>m;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>map[i][j];
if(i0 || j0 || in-1 || jm-1){
if(map[i][j]'0'){
vis[i][j]=1;
q.push({i,j});
}
}
}
}
bfs();
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(map[i][j]=='0' && !vis[i][j]){
ans++;
}
}
}
cout<<ans;
return 0;
}
//题解2025-09-20 来自 浙江
0
























有帮助,赞一个