宝岛探险2

来源:互联网 发布:ip网络广播防水音柱 编辑:程序博客网 时间:2024/04/29 16:19
#include<iostream>using namespace std;int book[51][51]={0};int a[51][51];int sum;int n,m;void dfs(int x,int y,int color){    int tx,ty;    int k;    //定义一个方向的数组    int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};    //枚举4个方向    a[x][y]=color;    for(k=0;k<4;k++)    {        //计算下一步的坐标        tx=x+next[k][0];        ty=y+next[k][1];        //判断是否越界        if(tx<1||tx>n||ty<1||ty>m)        {            continue;        }        //判断是否是陆地        if(a[tx][ty]>0&&book[tx][ty]==0)        {            sum++;            book[tx][ty]=1;//标记这个点已经走过            dfs(tx,ty,color);//开始尝试下一个点        }    }    return ;}int main(){    int i,j;    int num=0;    cin>>n>>m;    //读入地图    for(i=1;i<=n;i++)    {        for(j=1;j<=m;j++)        {            cin>>a[i][j];        }    }    //对每一个大于0的点尝试进行dfs染色    for(i=1;i<=n;i++)    {        for(j=1;j<=m;j++)        {            if(a[i][j]>0)            {                num--;                book[i][j]=1;                dfs(i,j,num);            }        }    }    //输出染色后的地图    for(i=1;i<=n;i++)    {        for(j=1;j<=m;j++)        {            cout<<a[i][j]<<" ";        }        cout<<endl;    }    cout<<"小岛个数:"<<-num<<endl;    return 0;}/*10 101 2 1 0 0 0 0 0 2 33 0 2 0 1 2 1 0 1 24 0 1 0 1 2 3 2 0 13 2 0 0 0 1 2 4 0 00 0 0 0 0 0 1 5 3 00 1 2 1 0 1 5 4 3 00 1 2 3 1 3 6 2 1 00 0 3 4 8 9 7 5 0 00 0 0 3 7 8 6 0 1 20 0 0 0 0 0 0 0 1 0*/


 

0 0
原创粉丝点击