码迷,mamicode.com
首页 > 其他好文 > 详细

宝岛探险2

时间:2015-08-13 22:24:59      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

#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 10
1 2 1 0 0 0 0 0 2 3
3 0 2 0 1 2 1 0 1 2
4 0 1 0 1 2 3 2 0 1
3 2 0 0 0 1 2 4 0 0
0 0 0 0 0 0 1 5 3 0
0 1 2 1 0 1 5 4 3 0
0 1 2 3 1 3 6 2 1 0
0 0 3 4 8 9 7 5 0 0
0 0 0 3 7 8 6 0 1 2
0 0 0 0 0 0 0 0 1 0
*/


 

版权声明:本文为博主原创文章,未经博主允许不得转载。

宝岛探险2

标签:

原文地址:http://blog.csdn.net/ingnight/article/details/47619113

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!