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.
Given a diagram of Farmer John's field, determine how many ponds he has.
输入
* 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.
输出
* Line 1: The number of ponds in Farmer John's field.
样例输入
10 12
W........WW.
.WWW.....WWW
....WW...WW.
.........WW.
.........W..
..W......W..
.W.W.....WW.
W.W.W.....W.
.W.W......W.
..W.......W.
样例输出
3
很经典的搜索问题,每找到一个water位’W',就进行dfs把它及它相连的water填充成 ‘.‘,将当前找到的lack抹去,防止重复计算lack。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 using namespace std; 3 char map[105][105]; 4 int dx[8]={-1,0,1,0,1,-1,-1,1}, 5 dy[8]={0,-1,0,1,1,-1,1,-1}; 6 void dfs(int x,int y); 7 int count=0,m,n; 8 int main() { 9 cin>>n>>m; 10 for(int i=0;i<n;i++) { 11 for (int j = 0; j < m; j++){ 12 cin >> map[i][j]; 13 } 14 } 15 for(int i=0;i<n;i++) { 16 for (int j = 0; j < m; j++){ 17 if(map[i][j]=='W') { 18 count++; 19 dfs(i,j); 20 } 21 } 22 } 23 cout<<count<<endl; 24 return 0; 25 } 26 void dfs(int x,int y) 27 { 28 map[x][y]='.'; 29 30 for(int i=0;i<8;i++){ 31 int px=x+dx[i],py=y+dy[i]; 32 if(px>=0&&px<n&&py>=0&&py<m&&map[px][py]=='W') 33 dfs(px,py); 34 } 35 }