Lake Counting
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 44131 | Accepted: 21800 |
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 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
Hint
OUTPUT DETAILS:
There are three ponds: one in the upper left, one in the lower left,and one along the right side.
Source
题意:
由于近日阴雨连天,约翰的农场中中积水汇聚成一个个不同的池塘,农场可以用 N x M (1 <= N <= 100; 1 <= M <= 100) 的矩形来表示。农场中的每个格子可以用'W'或者是'.'来分别代表积水或者土地,约翰想知道他的农场中有多少池塘。八连通的积水被认为是一块积水。
给你约翰农场的航拍图,确定有多少池塘?
Input
* 第1行:N 和 M
*第2行:N+1: M个字符一行,每个字符代表约翰的农场的土地情况。每个字符中间不包含空格。
Output
* 第1行:池塘的数量
题解:用深度搜索dfs,联通的只是一块,要把这一块都标记后,才能搜索下一块。
深度搜索dfs侧重于解决(求出符合题目要求的所有解法个数 )的问题。
与深度搜索dfs不同的是,广搜bfs旨在于找出最短的路径,最好的结果。
#include<iostream>
using namespace std;
const int MAX = 110;
int N,M;
char Map[MAX][MAX];
void dfs(int x,int y){
Map[x][y] = '.';
for(int dx = -1;dx <= 1;++dx){
for(int dy = -1;dy <= 1;++dy){
int nx = x + dx,ny = y + dy;
if(1 <= nx && nx <= N && 1 <= ny && ny <= M){
if(Map[nx][ny] == 'W'){
dfs(nx,ny);
}
}
}
}
}
int solve(){
int res = 0;
for(int i=1;i<=N;++i){
for(int j=1;j<=M;++j){
if(Map[i][j] == 'W'){
dfs(i,j);
res++;
}
}
}
return res;
}
int main(void){
cin >> N >> M;
for(int i=1;i<=N;++i){
for(int j=1;j<=M;++j){
cin >> Map[i][j];
}
}
cout << solve() << endl;
return 0;
}