[Python] Efficiently find adjacent entries in a matrix

Discussão em 'Python' iniciado por Stack, Julho 23, 2025.

  1. Stack

    Stack Membro Participativo

    Given a python matrix (or can be represented as a list as I know the number of rows and columns) I'm looking looking for an efficient way for finding the list of all number of adjacent entries of a given element. I can do this with an iteration by going over all adjacent places (beside, above, under and in diagonal) but I'm looking for a nicer and a more efficiente way.

    Example: Given a 25x25 matrix, all elements are initialized to 0

    DashBoard = [[0 for _ in range(25)] for _ in range(25)]


    The element I search the neighbors for is located at (10,10) There are entries at (10,9), (10,11) and (11,11)

    DashBoard[10][10] = 1

    DashBoard[10][9] = 1
    DashBoard[10][11] = 1
    DashBoard[11][11] = 1


    So the result I'm looking for is (3, 2), because there are 3 adjacent element horizontally ((10,9), (10,10), (10,11)) and 2 in diagonal ((10,10), (11,11))

    I don't know if numpy, pandas or any other built'in solution can do this.

    Any ideas?

    Continue reading...

Compartilhe esta Página