아마도이 파이썬 코드가 유용 할 수 있습니다. 기본적인 생각은 그리드의 첫 번째 탐색을 일종의 방식으로 수행하여 검정색 픽셀이 검은 색 이웃을 3 개 이상 보유하지 못하도록하는 것입니다. 그리드의 검은 색 부분에 해당하는 그래프는 원하는 결과가 나타나는 것처럼 나무입니다.
import Queue
import Image
import numpy as np
import random
#size of the problem
size = 50
#grid initialization
grid = np.zeros((size,size),dtype=np.uint8)
#start at the center
initpos = (size/2,size/2)
#create the propagation queue
qu = Queue.Queue()
#queue the starting point
qu.put((initpos,initpos))
#the starting point is queued
grid[initpos] = 1
#get the neighbouring grid cells from a position
def get_neighbours(pos):
n1 = (pos[0]+1,pos[1] )
n2 = (pos[0] ,pos[1]+1)
n3 = (pos[0]-1,pos[1] )
n4 = (pos[0] ,pos[1]-1)
return [neigh for neigh in [n1,n2,n3,n4]
if neigh[0] > -1 and \
neigh[0]<size and \
neigh[1] > -1 and \
neigh[1]<size \
]
while(not qu.empty()):
#pop a new element from the queue
#pos is its position in the grid
#parent is the position of the cell which propagated this one
(pos,parent) = qu.get()
#get the neighbouring cells
neighbours = get_neighbours(pos)
#legend for grid values
#0 -> nothing
#1 -> stacked
#2 -> black
#3 -> white
#if any neighbouring cell is black, we could join two branches
has_black = False
for neigh in neighbours:
if neigh != parent and grid[neigh] == 2:
has_black = True
break
if has_black:
#blackening this cell means joining branches, abort
grid[pos] = 3
else:
#this cell does not join branches, blacken it
grid[pos] = 2
#select all valid neighbours for propagation
propag_candidates = [n for n in neighbours if n != parent and grid[n] == 0]
#shuffle to avoid deterministic patterns
random.shuffle(propag_candidates)
#propagate the first two neighbours
for neigh in propag_candidates[:2]:
#queue the neighbour
qu.put((neigh,pos))
#mark it as queued
grid[neigh] = 1
#render image
np.putmask(grid,grid!=2,255)
np.putmask(grid,grid<255,0)
im = Image.fromarray(grid)
im.save('data.png')
여기 size = 50
및 size = 1000
또한 트리의 루트로 재생할 수 있습니다 설정 다른 설정 결과입니다.
다른 제한 사항이 있습니까? 그게 전부 일 뿐이라면, 흰색과 검은 색 줄을 번갈아 가며 스트라이프하고 검은 색 테두리를 단단히 고정 시키십시오. – Wug
대각선으로 놓여있는 세포는 이웃으로 간주 되는가 아니면 북쪽, 동쪽, 남쪽, 서쪽으로 4 개의 세포로 간주됩니까? – Astrotrain
하나의 2x1 검정색 요소를 흰색 그리드에 두는 것이 좋습니다? –