Sie könnten lernen, wie Sie breadth-first searches und depth-first searches implementieren, um Ihr Ziel zu erreichen. Das folgende Beispiel zeigt, wie beide Suchstrategien in einer Funktion einfach gehandhabt werden können. Ein modularer Ansatz sollte den Code einfach änderbar machen.
#! /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()
Stapelüberlauf ist kein Code-Schreibdienst. – MarkyPython
Dies könnte in Ihrer Forschung helfen: https://en.wikipedia.org/wiki/Flood_fill –
Scipy hat eine interessante Funktion, um dies zu erreichen: ['scipy.ndimage.measurements.label'] (http: //docs.scipy .org/doc/scipy-0.16.0/Referenz/generierte/scipy.ndimage.measurements.label.html) oder ['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