Lake Counting
| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 36120 | Accepted: 17934 |
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.
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.
* 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 12 W........WW. .WWW.....WWW ....WW...WW. .........WW. .........W.. ..W......W.. .W.W.....WW. W.W.W.....W. .W.W......W. ..W.......W.
Sample Output
3
AC代码:
#include<cstdio>
char s[110][110];
int n, m;
void dfs(int x, int y){
int next[8][2] = {{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1}};
s[x][y] = '.';
for(int k=0;k<=7;k++){
int tx, ty;
tx = x + next[k][0];
ty = y + next[k][1];
if(tx<1 || ty<1 || tx>n || ty>m) continue;
if(s[tx][ty] == 'W'){
dfs(tx, ty);
}
}
}
int main(){
scanf("%d%d", &n, &m);
getchar();
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
scanf("%c", &s[i][j]);
}
getchar();
}
int sum = 0;
for(int i = 1; i <= n; i++){
for(int j = 1;j <= m; j++){
if(s[i][j] == 'W'){
sum++;
dfs(i,j);
}
}
}
printf("%d",sum);
return 0;
}
湖泊计数算法
本文介绍了一个湖泊计数算法,该算法使用深度优先搜索(DFS)来遍历地图上的每个单元格,确定水区域是否构成独立的湖泊。湖泊定义为一个连通的水域集合,每个水域可以通过其八个相邻方向连接到其它水域。文章提供了完整的C++实现代码。
616

被折叠的 条评论
为什么被折叠?



