poj2386 Lake Counting

//挑战P33
// 输入 
/*
  注意下,使用gets()函数时,可能导致WA
  原因及应对见 http://blog.csdn.net/qwb492859377/article/details/48323443
  但是,能不用尽量不用吧!
*/

#include <iostream>
using namespace std;
int N, M; 
const int MAX_N = 105;
const int MAX_M = 105;
char field[MAX_N][MAX_M + 1]; //园子,注意字符串的结束符,导致的+1 

//现在位置(x, y)
void dfs(int x, int y)
{
	//将现在位置替换为 . 
	//使得其没有机会再自成一格水洼(因为这个水洼,要么在主函数中被访问了,要么和主函数中被访问的水洼连通,即为同一水洼
	field[x][y] = '.';
	
	//循环遍历移动的8个方向
	for (int dx = -1; dx <= 1; dx++)
	for (int dy = -1; dy <= 1; dy++)
	{
		//向x方向移动dx,向y方向移动dy,移动的结果为(nx, ny)
		int nx = x + dx, ny = y + dy; 
		// 判断(nx, ny)是不是在园子内,以及是否有积水
		if ( 0 <= nx && nx < N && 0 <= ny && ny < M && field[nx][ny] == 'W' ) dfs(nx, ny);
	 } 
	 return;
} 
 
void solve()
{
	int res = 0;
	for (int i = 0; i < N; i++)
	for (int j = 0; j < M; j++)
	if (field[i][j] == 'W')
	{
		dfs(i, j);
		res++;
	}
	cout << res << endl;
}

int main()
{
	cin >> N >> M;
	for(int i = 0; i < N; i++)
	for (int j = 0; j < M; j++)
	cin >> field[i][j];
	solve();
	return 0;
}

原文地址:https://www.cnblogs.com/mofushaohua/p/7789478.html