POJ 2386 Lake Counting

POJ 2386 Lake Counting

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
OUTPUT DETAILS:

There are three ponds: one in the upper left, one in the lower left,and one along the right side.
Source

USACO 2004 November

題目鏈接

題目大意:
上下左右任意方向相鄰的W爲同一個Lake,問給定圖有多少個Lake

題目思路:
每次BFS或DFS可訪問一個W及相鄰的所有W(一個Lake),並將它們標記爲已訪問。看所有W被訪問完需要多少次搜索,即有多少個Lake

以BFS舉例:從任意的一個W開始BFS,搜索到一個W就把它設置爲非W,直至此次BFS結束,Lake的數量加1;再從剩餘的W中進行BFS,同樣操作至結束,Lake數量加1;當圖中不存在W時,Lake即爲所求。
同樣原理的題目,這篇博客HDU1241,解法就是BFS。

但是此處採用DFS也可以解決

代碼:

#include<iostream>
#include<cstdlib>
#include<string>
using namespace std;
int n, m;
char lake[101][101];

void dfs(int i,int j)
{
	lake[i][j] = '.';
	for (int p = -1; p<= 1; p++)
	{
		for (int q = -1; q <= 1; q++)
		{
			int a = i + p, b = j + q;
			if (a >= 1 && a <= n && b >= 1 && b <= m && lake[a][b] == 'W') dfs(a, b);
		}	
	}
}

int main()
{
	int sum = 0;
	cin >> n >> m;
	for (int i = 1; i <= n; i++)
	{
		string s;
		cin >> s;
		for (int j = 0; j < m; j++)
		{
			if (s[j] == '.')lake[i][j + 1] = '.';
			else lake[i][j + 1] = 'W';
		}
	}
	for(int i=1;i<=n;i++)
		for(int j=1;j<=m;j++)
			if (lake[i][j] == 'W') {
				dfs(i,j);
				sum++;
			}
	cout << sum << endl;
	return 0;
}
發佈了69 篇原創文章 · 獲贊 34 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章