您的位置:首页 > 其它

宝岛探险2

2015-08-13 20:44 295 查看
#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
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: