我需要在Python程序中查找所有连接的细菌簇(4连通性)。输入是一个长这样的文件:
###
#####
#######
#######
######
###### ##
#### #####
## ###### ####
# ###### ####
### ########## #####
####### #### ## ######
######### ## # #####
# #### ### ###
##### #### # ## ##
##### ###### #
###### ########
#### ########
#######
#######
注意:紧贴网格边缘的簇不能被计算。
这个文件以二维数组的形式保存在我的类中。我编写了这个函数来查找所有簇,但它创建了太多的簇(22个而不是5个)。你有什么想法我可能做错了什么吗?
我的代码:
def findAll(self):
self.colonies = [set()]
for i in range(len(self.grid)):
for j in range(len(self.grid[i])):
if self.grid[i][j] == "#":
added = False
count = 0
for k in self.colonies:
if self.checkNeighbours((i, j), k):
k.add((i, j))
added = True
count += 1
if not added:
self.colonies.append({(i, j)})
def checkNeighbours(self, pos, current):
return ((pos[0] + 1, pos[1]) in current
or (pos[0] - 1, pos[1]) in current
or (pos[0], pos[1] + 1) in current
or (pos[0], pos[1] - 1) in current)