【问题标题】:Locate all similar "touching" elements in a 2D Array (Python) [closed]在二维数组(Python)中找到所有类似的“接触”元素[关闭]
【发布时间】:2016-07-08 13:03:59
【问题描述】:

假设我有数组:

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

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

我需要做什么才能开始研究这个?

编辑:结果证明这只是“Flood Fill”。

【问题讨论】:

  • 堆栈溢出不是代码编写服务。
  • 这可能对您的研究有所帮助:en.wikipedia.org/wiki/Flood_fill
  • Scipy 有一些有趣的功能可以实现这一点:scipy.ndimage.measurements.labelfind_objects
  • 请定义您的“感人”标准。如果将数组视为具有 N、E、S 和 W 方向的地图,您是否只包括那些在这些方向上相邻的块?您是否还包括在 NE、SE、SW 和 NW 方向上直接相邻的街区?您是否需要定义邻接矩阵来确定矩阵位置的邻居?
  • @NoctisSkytower 我会更新主帖,但你和其他人所说的大部分内容都涵盖了我的意图。它本来是 NESW,没有对角线。

标签: python arrays multidimensional-array python-3.5


【解决方案1】:

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

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

【讨论】:

  • 这就是我要找的,谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-12-21
  • 2021-02-21
  • 2021-09-22
  • 2017-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-23
相关资源
最近更新 更多