如何使用随机洪水填充来枚举Matrix的单元格?

时间:2014-10-01 00:55:43

标签: python random flood-fill

大多数洪水填充算法(动画)使用统一扩展,例如:

enter image description here

我在代码中实现了随机漫游,但问题在于它“忘记”某些单元格,如下图所示:

enter image description here

那么,我如何以随机方式填充矩阵并同时枚举单元格(访问过)?

如果您认为我的问题不符合网站的质量标准,请考虑添加评论。

1 个答案:

答案 0 :(得分:1)

尝试选择以下内容:

import numpy as np

N = 100
m = np.zeros((N, N))
# initial point to start random fill
i, j = np.random.randint(0, N, 2)
# mark as filled
m[i, j] = 1

active = [(i, j)] # add initial to active cells to expand from

while active:
    c = np.random.randint(0, len(active)) # choose random cell
    i, j = active[c] # get coordinates

    # get all neighbors
    neighbors = set([(min(N-1, max(0, x)), min(N-1, max(0, y))) for x in range(i-1, i+2) for y in range(j-1, j+2)])
    neighbors = [n for n in neighbors if m[n] == 0] # get all unmarked neighbors

    if neighbors:
        # choose random neighbor and mark it
        random_neighbor = neighbors[np.random.randint(0, len(neighbors))]
        m[random_neighbor] = 1       

        if len(neighbors) <= 1: # if there are no more unmarked neighbors left
            del active[c] # remove from active list

        active.append(random_neighbor) # add marked neighbor to active list
    else:
        del active[c]