AcWing 4959. 岛屿个数
原题链接
中等
作者:
噷梢
,
2025-04-05 19:43:48
· 福建
,
所有人可见
,
阅读 2
#include<bits/stdc++.h>
using namespace std;
const int N=55;
int g[N][N];
bool st[N][N];
int n,m;
int res;
int dx[]={1,-1,0,0};
int dy[]={0,0,1,-1};
void dfs_d(int x,int y){
st[x][y]=true;
for(int i=0;i<4;i++){
int a=x+dx[i],b=y+dy[i];
if(a<0||a>n+1||b<0||b>m+1)continue;
if(g[a][b]==0||st[a][b])continue;
dfs_d(a,b);
}
}
void dfs_h(int x,int y){
st[x][y]=true;
for(int i=-1;i<=1;i++){
for(int j=-1;j<=1;j++){
int a=x+i,b=y+j;
if(a<0||a>n+1||b<0||b>m+1)continue;
if(st[a][b])continue;
if(g[a][b]==0)dfs_h(a,b);
else {
dfs_d(a,b);
res++;
}
}
}
}
void slove(){
cin>>n>>m;
memset(st,false,sizeof st);
memset(g,0,sizeof g);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
char c;
cin>>c;
g[i][j]=c-'0';
}
}
dfs_h(0,0);
cout<<res<<endl;
res=0;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin>>t;
while(t--)
slove();
return 0;
}