'Python: floodfill algorithm for minesweeper
I'm writing a minesweeper game in python, and am currently trying to implement a floodfill algorithm. This is what I've written:
def floodfill(CURRENT_BOARD, row, col):
count = count_mines(row, col)
if count in POSSIBLE_MINE_NUMBERS:
CURRENT_BOARD[row][col] = str(count) + ' '
else:
if CURRENT_BOARD[row][col] == 'P ':
CURRENT_BOARD[row][col] = 'P '
if row > 0:
floodfill(CURRENT_BOARD, row - 1, col)
if row < len(BOARD[row]) - 1:
floodfill(CURRENT_BOARD, row + 1, col)
if col > 0:
floodfill(CURRENT_BOARD, row, col - 1)
if col < len(BOARD) - 1:
floodfill(CURRENT_BOARD, row, col + 1)
else:
CURRENT_BOARD[row][col] = ' '
if row > 0:
floodfill(CURRENT_BOARD, row - 1, col)
if row < len(BOARD[row]) - 1:
floodfill(CURRENT_BOARD, row + 1, col)
if col > 0:
floodfill(CURRENT_BOARD, row, col - 1)
if col < len(BOARD) - 1:
floodfill(CURRENT_BOARD, row, col + 1)
things to note:
POSSIBLE_MINE_NUMBERS = [1,2,3,4,5,6,7,8]
count_mines is a function that counts the number of mines in the surrounding 8 squares of row, col.
the board (CURRENT_BOARD) is a list of lists.
'P ' represents a flag, the algorithm is supposed to skip over flags.
' ' represents an empty space in the board.
The problem is when it is called, I get heaps of errors before it overflows the call stack, and I'm wondering what I've done wrong.
Solution 1:[1]
The following jumps out at me:
if CURRENT_BOARD[row][col] == 'P ':
CURRENT_BOARD[row][col] = 'P '
...
Here, you are recursing without modifying the board. This could well be the cause of the infinite recursion you're seeing.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | NPE |
