题目
有一个大小是 N * M 的花园,下雨后有积水。请求共有多少水洼。
例如:(W 代表积水, * 代表没有积水)
如下是两个水洼,与W相邻的没有其他积水;
* * * * * * W *
W * W W * *
* * * * * * * *
输入样例:(为图省事,空格代表了,其实应该输入)
N = 10, M = 12; (10行12列)
输出:3 (有3个水洼,如上图3个红色框)
java算法
/**
* @author yangshuai
* @version 创建时间:2015-10-15 下午6:16:47
* 类说明 :水洼算法
*
* 输入的院子数据
1 0 0 0 0 0 0 0 0 1 1 0
0 1 1 1 0 0 0 0 0 1 1 1
0 0 0 0 1 1 0 0 0 1 1 0
0 0 0 0 0 0 0 0 0 1 1 0
0 0 0 0 0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0 0 1 0 0
0 1 0 1 0 0 0 0 0 1 1 0
1 0 1 0 1 0 0 0 0 0 1 0
0 1 0 1 0 0 0 0 0 0 1 0
0 0 1 0 0 0 0 0 0 0 1 0
*/
public class LakeCountingAlgorithm {
/**
* 院子的长和宽
*/
private static int N; // 高
private static int M; // 宽
private static int[][] a;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入 N 的值");
N = scanner.nextInt();
System.out.println("请输入 M 的值");
M = scanner.nextInt();
// 存储数据{0 代表空地,1 代表积水}
a = new int[100][100];
System.out.println("请输入花园数据");
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
a[i][j] = scanner.nextInt();
}
}
// 开始计算
System.out.println("开始计算:" + System.currentTimeMillis());
int resultCount = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (a[i][j] == 1) {
solve(i, j);
resultCount ++;
}
}
}
System.out.println("完成计算:" + System.currentTimeMillis());
System.out.println("总共有 " + resultCount + " 处水洼");
}
/**
* 递归算法, (x, y)当前位置, 找到一处水洼,则把水洼中的积水都填成平地, 以保证计算可以结束
* @param x
* @param y
*/
public static void solve(int x, int y){
// 将当前位置重置数据为空地
a[x][y] = 0;
// 循环遍历周围的8个方向 (-1左 , 0中, 1右)
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <=1; j++) {
//获取周围的坐标点(dx, dy)
int dx = x + i;
int dy = y + j;
//判断这个点是否在花园里面而且有积水,则开始判定这个点周围有没有积水
if (dx >= 0 && dy >= 0 && dx < N && dy < M && a[dx][dy] == 1) {
solve(dx, dy);
}
}
}
}
}