| 4 | 4 | // |
| 5 | 5 | |
| 6 | 6 | export const annotate = (input) => { |
| 7 | | throw new Error('Remove this statement and implement this function'); |
| 7 | // Edge Case: empty grid with no rows |
| 8 | if (input.length === 0) { |
| 9 | return []; |
| 10 | } |
| 11 | |
| 12 | const rows = input.length; |
| 13 | const cols = input[0].length; |
| 14 | |
| 15 | // Edge Case: grid with no columns |
| 16 | if (cols === 0) { |
| 17 | return input; |
| 18 | } |
| 19 | |
| 20 | // Create a result grid as a copy of the input |
| 21 | const result = input.map(row => row.split('')); |
| 22 | |
| 23 | // Define the 8 possible directions for adjacent cells |
| 24 | const directions = [ |
| 25 | [-1, -1], [-1, 0], [-1, 1], |
| 26 | [0, -1], [0, 1], |
| 27 | [1, -1], [1, 0], [1, 1] |
| 28 | ]; |
| 29 | |
| 30 | // For each cell in the grid |
| 31 | for (let i = 0; i < rows; i++) { |
| 32 | for (let j = 0; j < cols; j++) { |
| 33 | // Edge Case: only process empty cells |
| 34 | if (result[i][j] === ' ') { |
| 35 | let flowerCount = 0; |
| 36 | |
| 37 | // Check all 8 adjacent cells |
| 38 | for (const [dx, dy] of directions) { |
| 39 | const ni = i + dx; |
| 40 | const nj = j + dy; |
| 41 | |
| 42 | // Edge Case: check bounds to avoid index out of range |
| 43 | if (ni >= 0 && ni < rows && nj >= 0 && nj < cols) { |
| 44 | // Edge Case: count adjacent flowers |
| 45 | if (result[ni][nj] === '*') { |
| 46 | flowerCount++; |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | // Edge Case: only replace empty cell with count if there are adjacent flowers |
| 52 | if (flowerCount > 0) { |
| 53 | result[i][j] = flowerCount.toString(); |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | // Convert each row back to a string |
| 60 | return result.map(row => row.join('')); |
| 8 | 61 | }; |
| 62 | |
| 63 | // Handled Edge Cases: empty grid with no rows, grid with no columns, only process empty cells, check bounds to avoid index out of range, count adjacent flowers, only replace empty cell with count if there are adjacent flowers |