在二维数组中定位所有类似的“接触”元素(Python)

2024-09-21 11:35:36 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个数组:

someArray = [["0","1","1","0"]
             ["0","1","0","1"]
             ["0","1","0","1"]
             ["0","1","1","0"]]

我想指出数组中的一个元素,然后能够识别每一个类似的“接触”元素(touch意味着如果将数组视为网格,它们将通过一个或多个连接进行连接)。例如,在本例中,如果我选择someArray[0][0],它会给我[1][0]、[2][0]和[3][0],因为所有这些元素都是“0”,并且彼此“接触”。我只指接触NESW,没有所说的方向的组合。在

我需要做些什么才能开始这项工作?在

编辑:原来这只是“洪水填充”。在


Tags: 网格元素编辑数组方向touch本例somearray
1条回答
网友
1楼 · 发布于 2024-09-21 11:35:36

您可以考虑学习如何实现breadth-first searches和{a2},以实现您的目标。下面的示例说明如何在一个函数中轻松处理这两种搜索策略。模块化的方法应该使代码易于更改。在

#! /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()

相关问题 更多 >

    热门问题