#include <bits/stdc++.h>
using namespace std;
int n, m;
int b1[4] = {0, 1, -1, 0};
int b2[4] = {1, 0, 0, -1};
char a[255][255];
bool jl[255][255];
int qo, qv;
int o, v;
void dfs(int x, int y) {
if (x < 0 || y < 0 || x >= n || y >= m || a[x][y] == '#') {
return;
}
if (jl[x][y]) {
return;
}
jl[x][y] = true;
if (a[x][y] == 'o') {
o++;
}
if (a[x][y] == 'v') {
v++;
}
for (int i = 0; i < 4; i++) {
dfs(x + b1[i], y + b2[i]);
}
}
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> a[i][j];
jl[i][j] = false;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (a[i][j] != '#' && !jl[i][j]) {
o = 0;
v = 0;
dfs(i, j);
if (o > v) {
qo += o;
} else {
qv += v;
}
}
}
}
cout << qo << " " << qv;
return 0;
}
D4181 流感传染
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, c = 0;
cin >> n;
int b[n+2][n+2]={0};
char a[n + 2][n + 2] = {'#'};
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> a[i][j];
if(a[i][j]=='@')
{
b[i][j]++;
}
}
}
int m;
cin >> m;
for (int k = 2; k < m; k++) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (a[i][j] == '@'&&b[i][j]>=1) {
if (a[i + 1][j] == '.') {
a[i + 1][j] = '@';
}
if (a[i][j + 1] == '.') {
a[i][j + 1] = '@';
}
if (a[i][j - 1] == '.') {
a[i][j - 1] = '@';
}
if (a[i - 1][j] == '.') {
a[i - 1][j] = '@';
}
b[i][j]++;
}
else
{
b[i][j]++;
}
}
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(a[i][j]=='@')
{
c++;
}
}
}
cout << c;
return 0;
}
D4331 【例8.2】细胞
#include<bits/stdc++.h>
using namespace std;
int n,m,ans;
int b1[4]{0,1,-1,0};
int b2[4]={1,0,0,-1};
char a[105][105];
struct f{
int x,y;
};
queue<f>q;
int main(){
cin>>n>>m;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>a[i][j];
}
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(a[i][j]>'0'){
ans++;
q.push({i,j});
while(q.size()>0){
f f1=q.front();
q.pop();
for(int j=0;j<4;j++){
if(f1.x+b1[j]>-1&&f1.x+b1[j]<n&&f1.y+b2[j]>-1&&f1.y+b2[j]<m&&a[f1.x+b1[j]][f1.y+b2[j]]>'0')
{
q.push({f1.x+b1[j],f1.y+b2[j]});
a[f1.x+b1[j]][f1.y+b2[j]]='0';
}
}
}
}
}
}
cout<<ans;
return 0;
}