[Solved] Locate all similar “touching” elements in a 2D Array (Python) [closed]


You might consider learning how to implement breadth-first searches and depth-first searches in order to accomplish your objective. The following example shows how both of these search strategies can be easily handled in one function. A modular approach should make the code simple to change.

#! /usr/bin/env python3
from collections import deque
from operator import eq


def main():
    """Show how to search for similar neighbors in a 2D array structure."""
    some_array = ((0, 1, 1, 0),
                  (0, 1, 0, 1),
                  (0, 1, 0, 1),
                  (0, 1, 1, 0))
    neighbors = (-1, 0), (0, +1), (+1, 0), (0, -1)
    start = 0, 0
    similar = eq
    print(list(find_similar(some_array, neighbors, start, similar, 'BFS')))


def find_similar(array, neighbors, start, similar, mode):
    """Run either a BFS or DFS algorithm based on criteria from arguments."""
    match = get_item(array, start)
    block = {start}
    visit = deque(block)
    child = dict(BFS=deque.popleft, DFS=deque.pop)[mode]
    while visit:
        node = child(visit)
        for offset in neighbors:
            index = get_next(node, offset)
            if index not in block:
                block.add(index)
                if is_valid(array, index):
                    value = get_item(array, index)
                    if similar(value, match):
                        visit.append(index)
        yield node


def get_item(array, index):
    """Access the data structure based on the given position information."""
    row, column = index
    return array[row][column]


def get_next(node, offset):
    """Find the next location based on an offset from the current location."""
    row, column = node
    row_offset, column_offset = offset
    return row + row_offset, column + column_offset


def is_valid(array, index):
    """Verify that the index is in range of the data structure's contents."""
    row, column = index
    return 0 <= row < len(array) and 0 <= column < len(array[row])


if __name__ == '__main__':
    main()

1

solved Locate all similar “touching” elements in a 2D Array (Python) [closed]