Lake Counting
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 45142 | Accepted: 22306 |
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.
/********************** author: yomi date: 18.8.14 ps:现在的行为大概像以卵击石,没办法,死也要挣扎着死。 **********************/ #include <iostream> #include <queue> #include <cstdio> using namespace std; const int maxn = 150; bool vis[maxn][maxn]; int m, n; char g[maxn][maxn]; struct Pos { int x, y; }p[maxn]; int dx[3] = {-1, 0, 1}; int dy[3] = {-1, 0, 1}; void bfs(int x, int y) { queue<Pos>q; while(!q.empty()){ q.pop(); } Pos p; p.x = x; p.y = y; q.push(p); vis[x][y] = true; while(!q.empty()){ Pos now = q.front(); q.pop(); for(int i=0; i<3; i++){ for(int j=0; j<3; j++){ int newX = now.x + dx[i]; int newY = now.y + dy[j]; if(newX<0||newX>=n||newY<0||newY>=m) continue; if(g[newX][newY]=='.') continue; if(!vis[newX][newY]){ Pos New; New.x = newX; New.y = newY; q.push(New); vis[newX][newY] = true; } } } } } int main() { cin >> n >> m; int ans = 0; for(int i=0; i<n; i++){ scanf("%s", g[i]); } for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ if(g[i][j] == 'W' && !vis[i][j]){ bfs(i, j); ans++; } } } cout << ans; return 0; } /** 10 12 W........WW. .WWW.....WWW ....WW...WW. .........WW. .........W.. ..W......W.. .W.W.....WW. W.W.W.....W. .W.W......W. ..W.......W. **/