Python: Floodfill Algorithm For Minesweeper
Solution 1:
I think you should revise your recursion algorithm:
- Operate only on covered tiles
- Find number of adjacent mines
- If there are any, reveal a numbered tile and stop recursion
- If not, reveal a blank tile and recusre
You should probably also think about how you store your board. At the moment you use the representation of the board to store the data. It might be a good idea to create a tile class and have a function that prints the board accordingly.
As for the number of adjacent mines: The mines never change, so you don't have to determine the count for each tile over and over again with a function. It is enough to determine it once after placing the mines and store the information. (If you use a class for tiles, I'd store the information there.)
Anyway, below is an implementation that uses your identification by string plus a set of tuple positions to represent the mines:
Covered = '---'
Flagged = '-P-'
board = []
for x inrange(12):
board += [[Covered] * 12]
mines = set([
(1, 12), (8, 2), (5, 5), (9, 4), (11, 11), (0, 9),
(5, 5), (6, 7), (9, 9), (9, 10), (11, 5)
])
defcount_mines(a, b):
c = 0if (a - 1, b - 1) in mines: c += 1if (a + 0, b - 1) in mines: c += 1if (a + 1, b - 1) in mines: c += 1if (a - 1, b + 0) in mines: c += 1if (a + 1, b + 0) in mines: c += 1if (a - 1, b + 1) in mines: c += 1if (a + 0, b + 1) in mines: c += 1if (a + 1, b + 1) in mines: c += 1return c
deffloodfill(board, row, col):
if board[row][col] == Covered:
count = count_mines(row, col)
if count > 0:
board[row][col] = ' ' + str(count) + ' 'else:
board[row][col] = ' 'if row > 0:
floodfill(board, row - 1, col)
if row < len(board[row]) - 1:
floodfill(board, row + 1, col)
if col > 0:
floodfill(board, row, col - 1)
if col < len(board) - 1:
floodfill(board, row, col + 1)
defshow(board):
for b in board:
print"".join(b)
floodfill(board, 0, 0)
show(board)
Solution 2:
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.
Post a Comment for "Python: Floodfill Algorithm For Minesweeper"