| 1 | 1 | def annotate(minefield): |
| 2 | | # Function body starts here |
| 3 | | pass |
| 2 | # Edge Case: Empty board |
| 3 | if not minefield: |
| 4 | return [] |
| 5 | |
| 6 | rows = len(minefield) |
| 7 | if rows == 0: |
| 8 | return [] |
| 9 | |
| 10 | cols = len(minefield[0]) |
| 11 | |
| 12 | # Edge Case: Irregular board dimensions |
| 13 | for row in minefield: |
| 14 | if len(row) != cols: |
| 15 | raise ValueError("The board is invalid with current input.") |
| 16 | |
| 17 | # Edge Case: Invalid characters in board |
| 18 | for row in minefield: |
| 19 | for char in row: |
| 20 | if char not in [' ', '*']: |
| 21 | raise ValueError("The board is invalid with current input.") |
| 22 | |
| 23 | # Create a result board with the same dimensions |
| 24 | result = [[' '] * cols for _ in range(rows)] |
| 25 | |
| 26 | # Directions for 8 neighbors (horizontal, vertical, diagonal) |
| 27 | directions = [ |
| 28 | (-1, -1), (-1, 0), (-1, 1), |
| 29 | (0, -1), (0, 1), |
| 30 | (1, -1), (1, 0), (1, 1) |
| 31 | ] |
| 32 | |
| 33 | for i in range(rows): |
| 34 | for j in range(cols): |
| 35 | # If the cell is a mine, keep it as is |
| 36 | if minefield[i][j] == '*': |
| 37 | result[i][j] = '*' |
| 38 | else: |
| 39 | # Count adjacent mines |
| 40 | count = 0 |
| 41 | for dx, dy in directions: |
| 42 | ni, nj = i + dx, j + dy |
| 43 | # Check if the neighbor is within bounds |
| 44 | if 0 <= ni < rows and 0 <= nj < cols: |
| 45 | if minefield[ni][nj] == '*': |
| 46 | count += 1 |
| 47 | |
| 48 | # If there are adjacent mines, replace with count |
| 49 | if count > 0: |
| 50 | result[i][j] = str(count) |
| 51 | |
| 52 | # Convert the result to list of strings |
| 53 | return [''.join(row) for row in result] |
| 54 | |
| 55 | # Handled Edge Cases: empty board, irregular board dimensions, invalid characters in board |