SDUT 2152 Balloons(DFS 四面+八面) 2010年山东省第一届ACM大学生程序设计竞赛

本文介绍了一种使用深度优先搜索(DFS)算法来统计二维网格中岛屿数量的方法,并提供了两种不同方向上的邻接矩阵定义,分别适用于四连通和八连通情况。通过具体的C++实现代码,展示了如何有效地遍历地图并标记已访问过的岛屿。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<map>
#include<cmath>
#include<queue>
#include<cmath>
#include<string>
#include<cstdio>
#include<stack>
#include<iostream>
#include<cstring>
#include<algorithm>
#define inf 0x3f3f3f3f
#define eps 1e-8
#define ls l,mid,rt<<1
#define rs mid+1,rt,rt<<1|1
#define LL __int64
#define ll long long
using namespace std;
char str[110][110];
bool vis[110][110];
int cx[]={0,-1,0,1},cy[]={1,0,-1,0};

int cx1[]= {-1 , -1 , -1 , 0 , 0 , 1 , 1 , 1};
int cy1[]={-1 , 0 , 1 , -1 , 1 , -1 , 0 , 1};
int n,ans1,ans2;

void dfs1(int x,int y){
    vis[x][y] = true;
    for(int i = 0;i < 4;++ i){

        int tx = x+cx[i];
        int ty = y+cy[i];
        if(tx>=0&&tx<n&&ty>=0&&ty<n&&str[tx][ty]=='1'&&!vis[tx][ty]){

            dfs1(tx,ty);
        }
    }
}

void dfs2(int x,int y){
    vis[x][y] = true;
    for(int i = 0;i < 8;++ i){
        int tx = x+cx1[i];
        int ty = y+cy1[i];
        if(tx>=0&&tx<n&&ty>=0&&ty<n&&str[tx][ty]=='1'&&!vis[tx][ty]){

            dfs2(tx,ty);
        }
    }
}
int main(){
    int i,j,k,cla = 1;
    while(~scanf("%d",&n)&&n){
        for(i = 0;i < n; ++ i){
            scanf("%s",str[i]);
        }
        ans1 = ans2 =0;
        memset(vis,false,sizeof(vis));
        for(i = 0;i < n;++ i){
            for(j = 0;j < n;++ j){
                if(!vis[i][j]&&str[i][j]=='1'){
                    ans1++;
                    dfs1(i,j);
                }
            }
        }
        memset(vis,false,sizeof(vis));
        for(i = 0;i < n;++ i){
            for(j = 0;j < n;++ j){
                if(!vis[i][j]&&str[i][j]=='1'){
                    ans2++;
                    vis[i][j]=true;
                    dfs2(i,j);
                }
            }
        }
        printf("Case %d: ",cla++);
        printf("%d %d\n\n",ans1,ans2);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值