这个题是要统计岛屿个数,但是不能算子岛屿的数量,这个就得找到那些成环的岛屿,但是这个操作我还不会,所以刚才又写了下只能拿一小半的分。
#include<bits/stdc++.h>
using namespace std;
int m,n,ans;
string maze[50];
struct node{
int x,y;
};
int dir[4][2]={{-1,0},{0,1},{1,0},{0,-1}};
bool check(int x,int y)
{
return x>=0&&x<m&&y>=0&&y<n;
}
void solve()
{
ans=0;
cin>>m>>n;
for(int i=0;i<m;i++)
cin>>maze[i];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(maze[i][j]=='1'){
ans++;
queue<node>q;
q.push({i,j});
while(!q.empty()){
node now=q.front();
maze[now.x][now.y]='#';
q.pop();
for(int i=0;i<4;i++){
int newx,newy;
newx=now.x+dir[i][0];
newy=now.y+dir[i][1];
if(check(newx,newy)&&maze[newx][newy]=='1'){
q.push({newx,newy});
maze[newx][newy]='#';
}
}
}
}
}
}
cout<<ans<<'\n';
}
int main()
{
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int t;
cin>>t;
while(t--)
solve();
return 0;
}
等我再看看怎么写。
好吧,感觉有点不想看别人的题解。但是自己又想不出来。
好了我回来了,这回已经A了,但是写得还是不是很好。
#include<bits/stdc++.h>
using namespace std;
int m,n,ans;
string maze[50];
struct node{
int x,y;
};
int dir[8][2]={{-1,0},{0,1},{1,0},{0,-1},{-1,-1},{1,1},{1,-1},{-1,1}};
bool check(int x,int y)
{
return x>=0&&x<m&&y>=0&&y<n;
}
bool bfs(int x,int y)
{
if(x==0||x==m-1||y==0||y==n-1) return true;//在边界 肯定不为子岛屿
string s[50];
for(int i=0;i<m;i++)
s[i]=maze[i];
queue<node>q;
q.push({x,y});
while(!q.empty()){
node now=q.front();
q.pop();
s[now.x][now.y]='*';
for(int i=0;i<8;i++){
int newx,newy;
newx=dir[i][0]+now.x;
newy=dir[i][1]+now.y;
if(!check(newx,newy)) return true; //如果这个海水在边界 肯定可以
if(s[newx][newy]=='0'){
q.push({newx,newy});
s[newx][newy]='*';
}
}
}
return false;
}
void solve()
{
ans=0;
cin>>m>>n;
for(int i=0;i<m;i++)
cin>>maze[i];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(maze[i][j]=='1'){
if(!bfs(i,j)) continue;
ans++;//如果能超出边界 则不是子岛屿
queue<node>q;
q.push({i,j});
while(!q.empty()){
node now=q.front();
maze[now.x][now.y]='#';
q.pop();
for(int i=0;i<4;i++){
int newx,newy;
newx=now.x+dir[i][0];
newy=now.y+dir[i][1];
if(check(newx,newy)&&maze[newx][newy]=='1'){
q.push({newx,newy});
maze[newx][newy]='#';
}
}
}
}
}
}
cout<<ans<<'\n';
}
int main()
{
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int t;
cin>>t;
while(t--)
solve();
return 0;
}
每次看这个陆地旁边的海洋能不能到地图边界,如果可以,那么必不为子岛屿,就加了一个判断的函数。也还行·。现在要继续变强啦。