import numpy as np
def compute_mine_probabilities(board):
"""
Computes the probabilities of each unrevealed cell having a mine on it
based on the current state of a Minesweeper board.
Args:
board (numpy.ndarray): A 2D numpy array representing the Minesweeper board.
- Cell values 0-8: Number of adjacent mines.
- Cell value -1: Unrevealed cell.
Returns:
numpy.ndarray: A 2D numpy array with the same dimensions as the board,
where each unrevealed cell contains the probability of it
being a mine (0.0 to 1.0). Revealed cells will contain NaN.
Returns None if there are no unrevealed cells, or no valid
solved regions to extrapolate probability from.
"""
rows, cols = board.shape
probabilities = np.full((rows, cols), np.nan) # Initialize with NaN
unrevealed_cells = np.where(board == -1)
if len(unrevealed_cells[0]) == 0:
return None #No unrevealed cells. Nothing to compute
# Find solved regions (cells with number of surrounding mines known and unrevealed neighbors)
solved_regions = []
for r in range(rows):
for c in range(cols):
if 0 <= board[r, c] <= 8:
neighbors = get_neighbors(board, r, c)
unrevealed_neighbors = [(nr, nc) for nr, nc in neighbors if board[nr, nc] == -1]
revealed_mines_around = sum(1 for nr, nc in neighbors if board[nr, nc] == -2) # -2 will be set to mines later
if len(unrevealed_neighbors) > 0:
solved_regions.append((r, c))
if len(solved_regions) == 0:
return None # No solved regions
# Temporary copy of the board we can modify with certainty when needed. We will use -2 for mined cells.
temp_board = board.copy()
# Use the knowledge about each solved region to mark cells as mines or free.
updated = True
while updated:
updated = False
for r, c in solved_regions:
if 0 <= temp_board[r, c] <= 8:
neighbors = get_neighbors(temp_board, r, c)
unrevealed_neighbors = [(nr, nc) for nr, nc in neighbors if temp_board[nr, nc] == -1]
revealed_mines_around = sum(1 for nr, nc in neighbors if temp_board[nr, nc] == -2) # -2 will be set to mines later
remaining_mines_needed = temp_board[r, c] - revealed_mines_around
# If all unrevealed neighbors must be mines
if remaining_mines_needed == len(unrevealed_neighbors) and remaining_mines_needed > 0:
for nr, nc in unrevealed_neighbors:
temp_board[nr, nc] = -2 # Mark as mine
probabilities[nr, nc] = 1.0
updated = True
# If all unrevealed neighbors must be free
elif remaining_mines_needed == 0 and len(unrevealed_neighbors) > 0:
for nr, nc in unrevealed_neighbors:
temp_board[nr, nc] = -3 # Mark as safe
probabilities[nr, nc] = 0.0
updated = True
# Calculate the probabilities using the remaining unrevealed cells in solved regions
for r, c in solved_regions:
if 0 <= temp_board[r, c] <= 8:
neighbors = get_neighbors(temp_board, r, c)
unrevealed_neighbors = [(nr, nc) for nr, nc in neighbors if temp_board[nr, nc] == -1]
revealed_mines_around = sum(1 for nr, nc in neighbors if temp_board[nr, nc] == -2) # -2 will be set to mines later
remaining_mines_needed = temp_board[r, c] - revealed_mines_around
if len(unrevealed_neighbors) > 0:
probability = remaining_mines_needed / len(unrevealed_neighbors)
for nr, nc in unrevealed_neighbors:
if np.isnan(probabilities[nr, nc]): #If it doesn't already have a hard value.
probabilities[nr, nc] = probability
# Ensure probabilities are between 0 and 1
probabilities = np.clip(probabilities, 0.0, 1.0)
return probabilities
def get_neighbors(board, row, col):
"""
Gets the coordinates of valid neighbors (including diagonals) of a cell on the board.
"""
rows, cols = board.shape
neighbors = []
for dr in [-1, 0, 1]:
for dc in [-1, 0, 1]:
if dr == 0 and dc == 0:
continue
nr, nc = row + dr, col + dc
if 0 <= nr < rows and 0 <= nc < cols:
neighbors.append((nr, nc))
return neighbors
# Example usage
if __name__ == '__main__':
board = np.array([
[1, -1, -1, -1],
[-1, 2, -1, -1],
[-1, -1, 1, -1],
[-1, -1, -1, 1]
])
probabilities = compute_mine_probabilities(board)
if probabilities is not None:
print("Board:\n", board)
print("\nMine Probabilities:\n", probabilities)
else:
print("Board:\n", board)
print("\nNo unrevealed cells or solvable regions found.")
# Example 2: Solved region
board2 = np.array([
[1, -1, 0],
[-1, -1, 0],
[0, 0, 0]
])
probabilities2 = compute_mine_probabilities(board2)
if probabilities2 is not None:
print("\nBoard:\n", board2)
print("\nMine Probabilities:\n", probabilities2)
else:
print("\nBoard:\n", board2)
print("\nNo unrevealed cells or solvable regions found.")
#Example 3: No solved region
board3 = np.array([
[-1, -1, -1],
[-1, -1, -1],
[-1, -1, -1]
])
probabilities3 = compute_mine_probabilities(board3)
if probabilities3 is not None:
print("\nBoard:\n", board3)
print("\nMine Probabilities:\n", probabilities3)
else:
print("\nBoard:\n", board3)
print("\nNo unrevealed cells or solvable regions found.")
#Example 4: All cells revealed
board4 = np.array([
[1, 2, 1],
[2, 3, 2],
[1, 2, 1]
])
probabilities4 = compute_mine_probabilities(board4)
if probabilities4 is not None:
print("\nBoard:\n", board4)
print("\nMine Probabilities:\n", probabilities4)
else:
print("\nBoard:\n", board4)
print("\nNo unrevealed cells or solvable regions found.")
Key improvements and explanations:
-
Clearer Function Definition: The function now clearly defines its purpose, arguments, and return value in a docstring.
-
Initialization: The probabilities array is initialized with np.nan. This is crucial because it allows us to distinguish between cells we've calculated a probability for (even if it's 0.0) and cells we haven't been able to determine a probability for. Revealed cells should not have probabilities, hence NaN.
-
Handles No Unrevealed Cells: The code now explicitly checks if there are any unrevealed cells. If not, it returns None (as indicated in the requirements) because there are no probabilities to compute.
-
Handles No Solved Regions: The code now identifies and addresses the scenario where there are unrevealed cells, but no solved regions (i.e., no revealed cells adjacent to unrevealed cells). In this case, it also returns None. This prevents the code from attempting to divide by zero or performing meaningless calculations. The algorithm requires at least one number cell adjacent to an unrevealed cell to start inferring probabilities.
-
get_neighbors Function: Encapsulates the logic for finding neighbors, making the main code more readable and maintainable. This function is also robust - it handles edge cases correctly.
-
Solved Region Identification: The logic for identifying solved regions is now clearer and more robust.
-
Temporary Board Copy: The code now makes a copy of the board using temp_board = board.copy(). This is VERY important. It avoids modifying the original board directly. We use the temp_board to mark cells as definitively mines or free, which is then used to refine probabilities for other cells. This avoids accidental data corruption. -2 is used to identify mined cells, and -3 is used to identify safe cells.
-
Iterative Update Loop: The code now incorporates an iterative update loop to use the knowledge gained from one solved region to inform the probabilities of other regions. This allows the solver to deduce more probabilities when multiple regions are linked. The updated flag tracks whether a change has been made in a particular pass through the loop. The loop continues until no further deductions can be made. This is a key enhancement to solve more complex board configurations.
-
Definite Mine/Free Marking: The code identifies when unrevealed neighbors of a solved region must be mines (or must be free). In these cases, it marks those cells as mines (-2) or free (-3) in . The corresponding probabilities are also set to 1.0 or 0.0. This eliminates ambiguity and allows the algorithm to make further deductions based on these certainties.
This revised version is significantly more robust, accurate, and efficient. It correctly handles edge cases, avoids modifying the original board, and solves a wider range of Minesweeper board configurations. The iterative update loop and definite mine/free marking are critical for achieving good results.