How to create sublists by obeying the cell connection in a matrix

Asked

Viewed 47 times

1

Friends, I am trying to create sublists from a matrix to segment cells that are connected, such as the matrix below: matriz utilizada no exemplo

From this matrix I get this list with the painted cells:

lista = [[1, 1], [2, 1], [2, 2], [2, 3], [2, 5], [2, 6], [3, 2], [3, 5], [3, 6], [6,1], [6, 4], [6, 5], [7,1], [7, 4], [7, 5]]

I wish as a result, sublists with the yellow cells, grouped like this:

[[1, 1], [2, 1], [2, 2], [2, 3], [3, 2]],
[[2, 5], [2, 6], [3, 5], [3, 6]]
[[6,1], [7,1]]
[[6, 4], [6, 5], [7, 4], [7, 5]]

I don’t know if it’s possible, but so far, with the function below:

def group_by_diff(group, diff=1):
    container = []
    new_group = [group[0]] 
    for i in range(1,len(group)):
        if((group[i][0] - group[i-1][0] > diff) or (group[i][1] - group[i-1][1] > diff)):
            container.append(new_group)
            new_group = [group[i]]
        else:
            new_group.append(group[i])
    if(len(new_group) > 0):
        container.append(new_group)
    return container

I get this result only:

[[1, 1], [2, 1], [2, 2], [2, 3]], 
[[2, 5], [2, 6], [3, 2]], 
[[3, 5], [3, 6]], 
[[6, 1]], 
[[6, 4], [6, 5], [7, 1]], 
[[7, 4], [7, 5]]

What does not meet, in this example created 6 sublists, where in fact only 4 agglomerations should be created, according to the image.

I hope I made myself understood. I thank you in advance.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.