1. 程式人生 > >Openjudge1388 Lake Counting【DFS/Flood Fill】

Openjudge1388 Lake Counting【DFS/Flood Fill】

title lac n+1 其他 content problem not pre any

http://blog.csdn.net/c20182030/article/details/52327948

1388:Lake Counting

總時間限制:
1000ms
內存限制:
65536kB
描述
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.
輸入
* 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.
輸出
* Line 1: The number of ponds in Farmer John‘s field.
樣例輸入
10 12
W........WW.
.WWW.....WWW
....WW...WW.
.........WW.
.........W..
..W......W..
.W.W.....WW.
W.W.W.....W.
.W.W......W.
..W.......W.
樣例輸出
3
提示
OUTPUT DETAILS:

There are three ponds: one in the upper left, one in the lower left,and one along the right side.
來源
USACO 2004 Novembe
題目大意
大雨過後,農夫John的農場被水淹沒不知所措
有了積水,農場地圖中‘W’代表積水,‘.‘代表幹燥的土地。八連通的積水在同一個水窪裏。農夫John想知道農場裏有多少水窪。
這是一道搜索題。與其他搜索題一樣,都是不斷地搜索,直到達到目的。但是,這道題的目的是什麽呢?
目的是求出有多少水窪,如果遞歸的話,怎麽才能知道求出了數量呢?
所以這樣,不能單純的只調用一次函數(主程序中),否則最多只會找出一個水窪。
我一開始是這樣想的,把每個水窪只留下一個W,其余換成幹燥,最後再看有幾個W。可是這樣搜索的時候,留下的W也會被搜到,搜到就會變成‘.‘,答案就會是0。為了避免這個問題,需要設立一個輔助數組或者把這個W換成另一個字符,但是這樣既浪費時間也浪費空間(還浪費我的腦容量)。
於是我把函數寫在循環裏,把一個水窪消滅幹凈後,水窪數量就加1。我用DFS,BFS實現了這個想法。

Openjudge1388 Lake Counting【DFS/Flood Fill】