Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 35139 | Accepted: 17450 |
Description
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.
Input
* Line 1: Two space-separated integers: N and M * Lines 2..N+1: M characters per line representing one row of Farmer John's field. Each character is either 'W' or '.'. The characters do not have spaces between them.
Output
* Line 1: The number of ponds in Farmer John's field.
Sample Input
10 12W........WW..WWW.....WWW....WW...WW..........WW..........W....W......W...W.W.....WW.W.W.W.....W..W.W......W...W.......W.
Sample Output
3
Hint
OUTPUT DETAILS: There are three ponds: one in the upper left, one in the lower left,and one along the right side.
Source
USACO 2004 November
问题链接:。
题意简述:给定m×n矩阵 (1 <= N <= 100; 1 <= M <= 100),其中'W'代表水域,'.'代表陆地,问有几片湖。
本题可以使用深度优先搜索求解,用广度优先搜索也可以求解,差别不大。
问题分析:这个题与《》完全相同,程序改两个字符,改了一下结束条件就通过了。
程序说明:
程序中的有关内容说明如下:
1.方向数组 使用方向数组后,各个方向的试探的程序就会变得简洁了,用循环处理即可。
2.避免重复搜索 将搜索过的节点设置为'.'(陆地),可以避免重复搜索,能够简化程序逻辑。
3.设置边界 通过设置边界,可以免去矩阵(二维数组)的边界判断,简化了程序逻辑。
该问题与图遍历中寻找联通块问题基本上是同构的,算法思路一致。
每当找到一个水域,只需要计数加一,并且使用DFS算法把与其相邻的8个水域擦除即可(避免重复计数)。
参考链接:
AC的C语言程序如下:
/* POJ2386 Lake Counting */#include#include #define DIRECTSIZE 8struct direct { int drow; int dcol;} direct[DIRECTSIZE] = { {0, -1}, {0, 1}, {-1, 0}, {1, 0}, {-1, -1}, {-1, 1}, {1, -1}, {1, 1}};#define MAXN 100char grid[MAXN+2][MAXN+2];void dfs(int row, int col){ int i; for(i=0; i