0
def floodfill(col,rowb,neigh,bombpos):
#neigh is number of bombs (neighbors) around the position (row,col)
try:
    neigh[rowb][col]
    bombpos[rowb][col]
    visit[rowb][col]
except IndexError:
    return
#if the position is an isolated position, i.e. there are no bombs adjacent to it;
if neigh[rowb][col] == 0:
    pygame.draw.rect(screen, (55, 55, 55), (1 + col * 30, 1 + rowb * 30, 28, 28))
    floodfill(col - 1, rowb, neigh, bombpos)
    floodfill(col, rowb - 1, neigh, bombpos)
    floodfill(col + 1, rowb, neigh, bombpos)
    floodfill(col, rowb + 1, neigh, bombpos)
    floodfill(col - 1, rowb-1, neigh, bombpos)
    floodfill(col+1, rowb + 1, neigh, bombpos)
    floodfill(col + 1, rowb-1, neigh, bombpos)
    floodfill(col-1, rowb + 1, neigh, bombpos)

I'm trying to recreate the minesweeper flood fill algorithm, so I have a flood fill function in which I recursively pick all the boxes around the ones that have a neighbor value of 0, meaning they are not touching any bombs. I understand why this is an infinite recursion, and that I must somehow use a visit matrix that detects which position has been tested so I can end eventually end the recursion. I have tried implementing a "visit" matrix which would be switched to true for a position (row,col) if the position is used in the recursion, but I could not get it to work at all. How could I implement the visit matrix in this code in order to get the proper flood fill algorithm used in minesweeper?

  • Welcome to SO. Unfortunately this isn't a discussion forum or tutorial service. Please take the time to read [ask] and the other links on that page. You should invest some time working your way through [the Tutorial](https://docs.python.org/3/tutorial/index.html), practicing the examples. It will give you an introduction to the tools Python has to offer and you may even start to get ideas for solving your problem. – wwii Dec 02 '17 at 06:06

1 Answers1

1

This is the code I found to work in case anyone has the same issue as me, I'm not sure why but using "try:" would stop the recursion for certain cases, so switching to a good-old fashion if not statement is better for setting the boundaries. Then it is simply a matter of setting the visit matrix to false once you "open" a cell.

   if not (-1<rowb<size and -1<col<size):
    return
if neigh[rowb][col] == 0 and not visit[rowb][col]:
    pygame.draw.rect(screen, (55, 55, 55), (1 + col * 30, 1 + rowb * 30, 28, 28))
    visit[rowb][col] = True
    floodfill(col - 1, rowb, neigh, bombpos)
    floodfill(col, rowb - 1, neigh, bombpos)
    floodfill(col + 1, rowb, neigh, bombpos)
    floodfill(col, rowb + 1, neigh, bombpos)
    floodfill(col - 1, rowb - 1, neigh, bombpos)
    floodfill(col - 1, rowb + 1, neigh, bombpos)
    floodfill(col + 1, rowb - 1, neigh, bombpos)
    floodfill(col + 1, rowb + 1, neigh, bombpos)