坑1:读入图的时候,不能把图当作数字来读,否则他会把一行的01都当成一个数字读进去,所以要按一个字符一个字符的读(不能用scanf,会出现奇怪的bug,建议用cin)
坑2:判断越界的时候,x<=n+1,y<=m+1 要注意不能把m写成n!
#include<bits/stdc++.h>
using namespace std;
const int N = 55;
int g[N][N];
typedef long long LL;
typedef pair<int,int> PII;
int T,n,m;
bool st[N][N];
LL res;
int dx_0[]={0,1,1,1,0,-1,-1,-1};
int dy_0[]={1,1,0,-1,-1,-1,0,1};
int dx_1[]={0,1,0,-1};
int dy_1[]={1,0,-1,0};
void bfs_1(int x,int y);
void bfs_0(int x,int y){
// cout<<x<<' '<<y<<endl;
st[x][y]=true;
queue<PII> q;
q.push({x,y});
while(q.size()){
PII u = q.front();
q.pop();
for(int i=0;i<8;i++){
int nx = u.first + dx_0[i];
int ny = u.second + dy_0[i];
if(nx<0||nx>n+1||ny<0||ny>m+1)continue;
if(st[nx][ny])continue;
if(g[nx][ny]==0){
st[nx][ny]=true;
q.push({nx,ny});
continue;
}
if(g[nx][ny]==1){
// cout<<nx<<' '<<ny<<endl;
st[nx][ny]=true;
bfs_1(nx,ny);
res++;
}
}
}
}
void bfs_1(int x,int y){
// cout<<"发现一个岛:"<<endl;
st[x][y]=true;
queue<PII> q;
q.push({x,y});
while(q.size()){
PII u = q.front();
q.pop();
// cout<<u.first<<" "<<u.second<<endl;
for(int i=0;i<4;i++){
int nx = u.first + dx_1[i];
int ny = u.second + dy_1[i];
if(nx<0||nx>n+1||ny<0||ny>m+1)continue;
if(st[nx][ny])continue;
if(g[nx][ny]==1){
st[nx][ny]=true;
q.push({nx,ny});
}
}
}
}
int main(){
cin>>T;
while(T--){
// cout<<"请输入:"<<endl;
cin>>n>>m;
// cout<<n<<" "<<m<<endl;
memset(g,0,sizeof g);
memset(st,false,sizeof st);
res=0;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
char ch;
cin>>ch;
g[i][j]=ch-'0';
}
}
bfs_0(0,0);
cout<<res<<endl;
}
return 0;
}