地址:http://acm.nyist.net/JudgeOnline/problem.php?pid=27
水池数目
时间限制:3000 ms | 内存限制:65535 KB
难度:4
-
描述
-
南阳理工学院校园里有一些小河和一些湖泊,现在,我们把它们通一看成水池,假设有一张我们学校的某处的地图,这个地图上仅标识了此处是否是水池,现在,你的任务来了,请用计算机算出该地图中共有几个水池。
-
输入
-
第一行输入一个整数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
-
第一行输入一个整数N,表示共有N组测试数据
思路:
先用广度搜索,判断为0,,就赋值为2,返回,判断为2,直接返回,判断为1的时候就进行4个方向的判断,走过的地方就赋值为2,避免再次遍历。直到找到所有水池。虽然难度是4,但是做过类似的话,就思路很清晰,很简单。
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner cin =new Scanner(System.in);
int n=cin.nextInt();
while(n-->0){
int account=0;
int row=cin.nextInt();
int columns=cin.nextInt();
int[][] pools=new int[row][columns];
for(int i=0;i<row;i++)
for(int j=0;j<columns;j++)
pools[i][j]=cin.nextInt();
for(int i=0;i<row;i++)
for(int j=0;j<columns;j++)
if(findPools(pools,row,columns,i,j)){
isPools=false; //直到一条路径遍历完后就为假
account++;
}
System.out.println(account);
}
}
static boolean isPools=false; //用来标示这条路径是否为水池
//313 1937
public static boolean findPools(int [][] pools,int row,int columns,int r,int c){
if(r<0||c<0||r>=row||c>=columns||pools[r][c]==2) //边界及走过的路径
return false;
if(pools[r][c]==0){ //没有水池,已走过
pools[r][c]=2;
return false;
}
//剩下就是等于1的情况
pools[r][c]=2; //走过赋值为2
isPools=true; //设计有点巧妙,是1的情况就为真,
//上面
findPools(pools, row, columns, r-1, c);
//右边
findPools(pools, row, columns, r, c+1);
//下面
findPools(pools, row, columns, r+1, c);
//左边
findPools(pools, row, columns, r, c-1);
return isPools;
}
}