[Python] Breadth-first search on numpy array for consecutive adjacent zeroes

Discussão em 'Python' iniciado por Stack, Fevereiro 5, 2025.

  1. Stack

    Stack Membro Participativo

    I have a numpy array that looks like the following:

    arr = np.array([[-1, -1, -1, 0, -1]
    [ -1, -1, -1, 0, -1]
    [ -1, 0, -1, -1, 0]
    [ -1, 0, -1, -1, -1]
    [ -1, -1, -1, -1, 0]])


    I want each consecutive region marked with a 0 (including diagonals) to be changed to a different value, such that my array would end up looking like this:

    arr = np.array([[ -1, -1, -1, 1, -1]
    [ -1, -1, -1, 1, -1]
    [ -1, 2, -1, -1, 1]
    [ -1, 2, -1, -1, -1]
    [ -1, -1, -1, -1, 3]])


    One way of doing this could be through a breadth-first search. Is there any convenient way to do this, or is there an easier method available?

    Continue reading...

Compartilhe esta Página