POJ 2386 Lake Counting

题目链接:POJ 2386

Description

由于近日阴雨连天,约翰的农场中中积水汇聚成一个个不同的池塘,农场可以用 N x M (1 <= N <= 100; 1 <= M <= 100) 的正方形来表示。农场中的每个格子可以用'W'或者是'.'来分别代表积水或者土地,约翰想知道他的农场中有多少池塘。池塘的定义:一片相互连通的积水。任何一个正方形格子被认为和与它相邻的8个格子相连。

给你约翰农场的航拍图,确定有多少池塘

Input

* Line 1: N 和 M

* Lines 2..N+1: M个字符一行,每个字符代表约翰的农场的土地情况。每个字符中间不包含空格

Output

* Line 1: 池塘的数量

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

题意

池子是八连通的,问有多少池塘。

题解:

DFS水题中的水题,深搜,从碰到的第一个水格子开始,进入dfs函数,把这个点能到达的所有点都变成.,同时计数++。

代码

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<cstring>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>

using namespace std;

typedef long long ll;

const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 0x3f3f3f3f;
const int N = 2e5 + 5;
//int dir[4][2] = { 1,0,0,1,-1,0,0,-1 };
char feld[110][110];
int n, m;
void dfs(int x, int y) {
	feld[x][y] = '.';
	int nx, ny;
	for(int i(-1);i<2;i++)
		for (int j(-1); j < 2; j++) {
			nx = x + i;
			ny = y + j;
			if (nx >= 0 && ny >= 0 && nx < n&&ny < m&&feld[nx][ny] == '@') {
				dfs(nx, ny);
			}
		}
}
int main() {
	int num;
	while (cin >> n >> m,n) {
		num = 0;
		memset(feld, 0, sizeof(feld));
		for (int i(0); i < n; i++) {
			cin >> feld[i];
		}
		for(int i(0);i<n;i++)
			for (int j(0); j < m; j++) {
				if (feld[i][j] == '@') {
					dfs(i, j);
					num++;
				}
			}
		cout << num << endl;
	}
}
posted @ 2018-09-05 16:38  Titordong  阅读(152)  评论(0编辑  收藏  举报