程序设计:院子积水问题Lake Counting

来源:互联网 发布:科研设计 软件 编辑:程序博客网 时间:2024/04/28 02:15

Lake Counting

原英文描述:
Due to recent rains, water has pooled in various places in Farmer John’s field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) squares. Each square contains either water (‘W’) or dry land (‘.’). Farmer John would like to figure out how many ponds have formed in his field. A pond is a connected set of squares with water in them, where a square is considered adjacent to all eight of its neighbors.

Given a diagram of Farmer John’s field, determine how many ponds he has.
这里写图片描述
这里写图片描述
这里写图片描述

思路:
采用深度优先(DFS)的方法,可以从任意的 W 开始,不停地把邻接的W部分用 ‘.’ 代替。1次DFS后与初始的这个 W 连接的所有 W 就都被替换成了 ‘.’ ,因此直到图中不再存在 W 为止,总共进行DFS的次数就是答案了。8个方向共对应了8种状态转移,每个格子作为DFS的参数至多被调用一次,所以复杂度为O(8×N×M)=O(N×M)。

代码部分:

// 输入int N, M;char field[MAX_N][MAX_M + 1]; // 园子// 现在位置(x,y)void dfs(int x, int y) {// 将现在所在位置替换为.field[x][y] = '.';// 循环遍历移动的8个方向for (int dx = -1; dx <= 1; dx++) {    for (int dy = -1; dy <= 1; dy++) {// 向x方向移动dx,向y方向移动dy,移动的结果为(nx,ny)int nx = x + dx, ny = y + dy;// 判断(nx,ny)是不是在园子内,以及是否有积水if (0 <= nx && nx < N && 0 <= ny && ny < M && field[nx][ny] == 'W')   dfs(nx, ny);    }}return ;}void solve() {int res = 0;for (int i = 0; i < N; i++) {    for (int j = 0; j < M; j++) {        if (field[i][j] == 'W') {            // 从有W的地方开始dfs            dfs(i, j);            res++;        }    }}printf("%d\n", res);}
0 0