0

Most of the flood-filling algorithms (animated) use an uniform expansion, for example:

enter image description here

I implemented random walks in my code, but the problem is that it "forgets" some cells, like in the following picture:

enter image description here

So, how I can flood fill a Matrix and enumerate the cells (visited) at the same time in a random way?

Please, if you think that my question doesn't fit the quality standards of the site consider adding a comment.

Rosenthal
  • 149
  • 1
  • 2
  • 11

1 Answers1

1

Try selecting something like this:

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]
wasserfeder
  • 476
  • 2
  • 9
  • sintax errors (fixed): m[n] == 0 and for x in range(i-1, i+2) – Rosenthal Oct 01 '14 at 02:35
  • 1
    @Neo This will probably be very slow due to the loop – wasserfeder Oct 01 '14 at 02:36
  • @Neo I corrected the errors. Sorry, I wrote the code in a hurry, without running it in python. I'll check it now. – wasserfeder Oct 01 '14 at 02:38
  • ValueError: low >= high => from random module at line 12 – Rosenthal Oct 01 '14 at 02:39
  • @Neo I corrected the error. The problem appeared when a cell in the `active` list had no unmarked neighbor. – wasserfeder Oct 01 '14 at 02:52
  • 1
    It works but I think I have a better idea, this flood-fill approach is too slow, I will generate a list with the shape of the array as the range and assign each cell an unique value from this list using as the index a mix of distance from the central point and a random shift, this will only enumerate the array which is enough for me. Thanks for your time. Something like this: http://upload.wikimedia.org/math/b/3/7/b372d7f188a3b18456d2d25d25535e5d.png – Rosenthal Oct 01 '14 at 03:19