| 8 | 9 | * @returns {string[]} |
| 9 | 10 | */ |
| 10 | 11 | export const annotate = (input) => { |
| 11 | | throw new Error('Remove this line and implement the function'); |
| 12 | // Edge Case: Empty board (0x0) |
| 13 | if (!input || input.length === 0) { |
| 14 | return []; |
| 15 | } |
| 16 | |
| 17 | const rows = input.length; |
| 18 | const cols = input[0].length; |
| 19 | |
| 20 | // Edge Case: Board with no columns |
| 21 | if (cols === 0) { |
| 22 | return input.map(() => ''); |
| 23 | } |
| 24 | |
| 25 | // Create a result board |
| 26 | const result = Array(rows).fill().map(() => Array(cols).fill(' ')); |
| 27 | |
| 28 | // Directions for 8 adjacent cells (horizontal, vertical, diagonal) |
| 29 | const directions = [ |
| 30 | [-1, -1], [-1, 0], [-1, 1], |
| 31 | [0, -1], [0, 1], |
| 32 | [1, -1], [1, 0], [1, 1] |
| 33 | ]; |
| 34 | |
| 35 | // Process each cell |
| 36 | for (let i = 0; i < rows; i++) { |
| 37 | for (let j = 0; j < cols; j++) { |
| 38 | // If current cell is a mine, keep it as mine |
| 39 | if (input[i][j] === '*') { |
| 40 | result[i][j] = '*'; |
| 41 | } else { |
| 42 | // Count adjacent mines |
| 43 | let mineCount = 0; |
| 44 | |
| 45 | // Check all 8 directions |
| 46 | for (const [dx, dy] of directions) { |
| 47 | const ni = i + dx; |
| 48 | const nj = j + dy; |
| 49 | |
| 50 | // Edge Case: Check boundaries to avoid index out of bounds |
| 51 | if (ni >= 0 && ni < rows && nj >= 0 && nj < cols) { |
| 52 | if (input[ni][nj] === '*') { |
| 53 | mineCount++; |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | // If there are adjacent mines, put the count in the result |
| 59 | // Edge Case: Empty square with no adjacent mines remains empty |
| 60 | if (mineCount > 0) { |
| 61 | result[i][j] = mineCount.toString(); |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | // Convert result array to array of strings |
| 68 | return result.map(row => row.join('')); |
| 12 | 69 | }; |
| 70 | |
| 71 | // Handled Edge Cases: empty board (0x0), board with no columns, board edges and corners adjacency, empty square with no adjacent mines |
| 72 | } |