【DFS】Lake Counting(C++)

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

这题我也看不懂
大意是:有一块N×M的土地,雨后积起了水,有水标记为‘W’,干燥为‘.’。八连通的积水被认为是连接在一起的。请求出院子里共有多少水洼?
(题意可能有偏差)
这题思路是:先从第一个点开始,如果找到了一个点为‘W’,则将那一块的水洼扫除,同时累加器加1,然后继续找,一直到最后一个点。
接下来是AC代码:

#include 		//万能头文件。 
using namespace std;
char a[108][108];		//输入数据。
bool a1[108][108];
int n,m,sum=0;		//定义输入数据的长、宽,和累加器。
void DFS(int i,int j) {
	if(a1[i][j]==true) {		//如果这个位置为真。
		a1[i][j]=false;			//清除积水。
		DFS(i+1,j+1);		//向右下搜索。
		DFS(i-1,j-1);		//向左上搜索。
		DFS(i-1,j+1);		//向右上搜索。
		DFS(i+1,j-1);		//向左下搜索。
		DFS(i,j+1); 	    //向右搜索。
		DFS(i,j-1);		    //向左搜索。
		DFS(i-1,j);		    //向上搜索。
		DFS(i+1,j);		    //向下搜索。
	} else
		return;
}
int main() {
	cin>>n>>m;		//输入长、宽。
	memset(a1,false,sizeof(a1));		//全部定义为假
	for(int i=1; i<=n; i++) {		//输入 
		for(int j=1; j<=m; j++) {
			cin>>a[i][j];
			if(a[i][j]=='W')
				a1[i][j]=true;
		}
	}
	for(int i=1; i<=n; i++) {		//用双重循环来搜索 
		for(int j=1; j<=m; j++) {
			if(a1[i][j]==true) {
				DFS(i,j);
				sum++;
			}
		}
	}
	cout<<sum<<endl;

	return 0;
}

你可能感兴趣的:(入门oj)