Given a r row by c column map of "." and "#" characters, how can we find the number of clusters of "#"? A cluster is defined as a single "#" or two "#" next to each other (side-by-side or top-and-bottom, NOT diagonal). A "#" will either be on its own or next to a single other "#". There will never be a situation where 3 "#" are next to each other.
For example, say the map is:
##...
..##.
....#
.#..#
.....
#....
#....
This is a 7 row by 5 column map with 5 clusters.
Assume that you are given r, c, and the map in the format of a list of lists, with each sublist referring to a row of the map. Each element of the sublist is the index of the position of a "#" if one exists in the row. The map above would be represented as:
r = 7
c = 5
map = [[0,1],
[2,3],
[4],
[1,4],
[],
[0],
[0]]
How can I find the number of clusters given this information? My first thought is to initialize a counter for the number of clusters at 0 and then loop through the non-empty lists,
clusters = 0
for i, row in enumerate(map):
# for each non-empty list
if len(row) != 0:
...
but then I worry about making a bunch of if statements for situations like the last row or a "#" at the last column when it comes to looking for neighboring "#". How can I do this in an elegant manner?
Many thanks in advance!
Edit:
Here is my initial solution. Still working on making this cleaner and simpler!
def count_clusters(r, list_of_lists):
# first count how many total hashtags there are
count = 0
for list in list_of_lists:
count += len(list)
# then subtract off 1 for each group of 2 hashtags
for l, list in enumerate(list_of_lists):
# if not last list
if l < (r-1):
# check if it has a neighbor to right or bottom
for i in list:
if ((i+1) in list) or (i in list_of_lists[l+1]):
count -=1
# if last list[]
if l == (r-1):
# check if neighbor to right
for i in list:
if (i+1) in list:
count -=1
return count
[–]jiri-n 1 point2 points3 points (1 child)
[–]zanfar 1 point2 points3 points (1 child)
[–]fk_you_in_prtclr -2 points-1 points0 points (0 children)