目的を達成するためにbreadth-first searchesとdepth-first searchesの実装方法を学ぶことを検討することがあります。次の例は、これらの検索方法の両方を1つの関数で簡単に処理する方法を示しています。モジュラーアプローチは、コードを簡単に変更する必要があります。
#! /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()
スタックオーバーフローはコード書き込みサービスではありません。 – MarkyPython
これはあなたの研究に役立つかもしれません:https://en.wikipedia.org/wiki/Flood_fill –
Scipyはこれを達成するための興味深い機能を持っています:['scipy.ndimage.measurements.label'](http://docs.scipy .org/doc/scipy-0.16.0/reference/generated/scipy.ndimage.measurements.label.html)または['find_objects'](http://docs.scipy.org/doc/scipy-0.16.0/ reference/generated/scipy.ndimage.measurements.find_objects.html#scipy.ndimage.measurements.find_objects) – MSeifert