题目描述
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.
由于近期的降雨,雨水汇集在农民约翰的田地不同的地方。我们用一个NxM(1<=N<=100;1<=M<=100)网格图表示。每个网格中有水('W') 或是旱地('.')。一个网格与其周围的八个网格相连,而一组相连的网格视为一个水坑。约翰想弄清楚他的田地已经形成了多少水坑。给出约翰田地的示意图,确定当中有多少水坑。
输入格式
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.
第1行:两个空格隔开的整数:N 和 M 第2行到第N+1行:每行M个字符,每个字符是'W'或'.',它们表示网格图中的一排。字符之间没有空格。
输出格式
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
因为是翻译过来的题,我也不知道叫什么,就随便给个名叫水坑问题
我觉得这是一个BFS(DFS,BFS没啥区别,会写就行,只是个函数名)
根据输出的结果,再参照图说明对于一个小水坑如果它八个方向有小水坑那么就是一个大水坑
只要能找到一个大水坑的一个边角,就能找到整个大水坑,找边角可以直接暴力枚举,那么怎么保证新找到的水坑不是之前已经找过的,只要把之前的水坑都填上就行了
要建立一个更大的二维数组,把农田包在里面,最外面的一圈‘围栏’都当作旱地,可以省去判断某个小水坑在不在边界,八个方向会不会超出数组的麻烦。
n,m = map(int,input().split())
lst = [['.']*(m+2) for i in range(n+2)] # lst = [['.']*(m+2)]*(n+2) 这个方法建立的数组会导致每一行都联动
for i in range(1,n+1): # 把农田情况填到数组中间去
st1 = input()
for j in range(m):
lst[i][j+1] = st1[j]
ans = 0
lst1 = [[1,1],[1,0],[1,-1],[-1,0],[0,-1],[0,1],[-1,-1],[-1,1]] # 八个方向数组
def BFS(x,y):
lst[x][y] = '.' # 填土
for i in lst1:
if lst[x+i[0]][y+i[1]] == 'W': # 八个方向判断
BFS(x+i[0],y+i[1])
for i in range(1,n+1): # 找水坑的’衣角‘
for j in range(1,m+1):
if lst[i][j] == 'W':
ans += 1
BFS(i,j)
print(ans)