洛谷P1596 [USACO10OCT]湖计数Lake Counting

版权声明:晓程原创 https://blog.csdn.net/qq_43469554/article/details/89096350

由于近期的降雨,雨水汇集在农民约翰的田地不同的地方。我们用一个NxM(1<=N<=100;1<=M<=100)网格图表示。每个网格中有水(‘W’) 或是旱地(’.’)。一个网格与其周围的八个网格相连,而一组相连的网格视为一个水坑。约翰想弄清楚他的田地已经形成了多少水坑。给出约翰田地的示意图,确定当中有多少水坑。

输入格式:
第1行:两个空格隔开的整数:N 和 M 第2行到第N+1行:每行M个字符,每个字符是’W’或’.’,它们表示网格图中的一排。字符之间没有空格。

输出格式:
一行:水坑的数量

开始没看懂水坑,看完题解才发现它描述的是连通块==

#include <iostream>
using namespace std;
char s[105][105];
int n, m;
void dfs(int x, int y)
{
	s[x][y] = '.';//用自身标记
	for (int x0 = -1; x0 <= 1; x0++)
	{
		for (int y0 = - 1; y0 <= 1; y0++)
		{
			int tx = x0 + x;
			int ty = y0 + y;
			if (tx < 0 || tx >= n || ty < 0 || ty >= m)
			{
				continue;
			}
			if (s[tx][ty] == 'W')
			{
				//搜完一个水坑继续搜下个 
				dfs(tx, ty);
			}
		}
	}
}
int main()
{
	int ans = 0;
	cin >> n >> m;
	for (int i = 0; i < n; i++)
	{
		scanf("%s", s[i]);
	}
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			if (s[i][j] == 'W')
			{
				dfs(i, j);
				ans++;
			}
		}
	}
	cout << ans << endl;
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_43469554/article/details/89096350