找到所有相似的"触摸"二维数组中的元素(Python)

时间:2016-03-21 20:26:24

标签: python arrays multidimensional-array python-3.5

让我们说我有阵列:

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)

    coordinator.animateAlongsideTransition({ (coordinator) -> Void in
        // do your stuff here
        // here the frame has the new size
    }, completion: nil)
}

我想指出数组中的一个元素,然后能够识别每个类似的"触摸" element(触摸意味着如果将数组视为网格,则它们将通过一个或多个连接进行连接)。例如,在这种情况下,如果我选择someArray [0] [0],它会给我[1] [0],[2] [0]和[3] [0],因为所有这些元素都是& #34; 0",并且"触摸"另一个。我只是说触摸NESW,没有所说方向的组合。

我需要做些什么才能开始这方面的工作?

编辑:结果只是"洪水填充"。

1 个答案:

答案 0 :(得分:2)

您可以考虑学习如何实施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()