水池数目

http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=27

描述

南阳理工学院校园里有一些小河和一些湖泊,现在,我们把它们通一看成水池,假设有一张我们学校的某处的地图,这个地图上仅标识了此处是否是水池,现在,你的任务来了,请用计算机算出该地图中共有几个水池。

输入

第一行输入一个整数N,表示共有N组测试数据
每一组数据都是先输入该地图的行数m(0<m<100)与列数n(0<n<100),然后,输入接下来的m行每行输入n个数,表示此处有水还是没水(1表示此处是水池,0表示此处是地面)

输出

输出该地图中水池的个数。
要注意,每个水池的旁边(上下左右四个位置)如果还是水池的话的话,它们可以看做是同一个水池。

样例输入

2
3 4
1 0 0 0 
0 0 1 1
1 1 1 0
5 5
1 1 1 1 0
0 0 1 0 1
0 0 0 0 0
1 1 1 0 0
0 0 1 1 1

样例输出

2
3
#include<stdio.h>
#include<string.h>
#define N 120
int a[N][N],book[N][N],m,n;
int dfs(int x,int y,int color)
{
	int next[4][2]={
					0,1,
					1,0,
					0,-1,
					-1,0
				};
	int k,tx,ty;
	a[x][y]=color;
	for(k=0;k<4;k++)
	{
		tx=x+next[k][0];
		ty=y+next[k][1];
		if(tx>n||tx<1||ty<1||ty>m)
			continue;
		if(a[tx][ty]>0&&book[tx][ty]==0)
		{
			book[tx][ty]=1;
			dfs(tx,ty,color);
		}
	}
}
int main()
{
	int i,j,t,num;
	scanf("%d",&t);
	while(t--)
	{
		num=0;
		memset(a,0,sizeof(a));
		memset(book,0,sizeof(book));
		scanf("%d%d",&n,&m);
		for(i=1;i<=n;i++)
			for(j=1;j<=m;j++)
				scanf("%d",&a[i][j]);
		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);
				}
			}
		printf("%d
",-num);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/zyq1758043090/p/10002953.html