| 8 | 9 | * @returns {string[]} |
| 9 | 10 | */ |
| 10 | 11 | export const annotate = (input) => { |
| 11 | | throw new Error('Remove this statement and implement this function'); |
| 12 | // Edge Case: Empty grid with no rows |
| 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: Grid with no columns |
| 21 | if (cols === 0) { |
| 22 | return input; |
| 23 | } |
| 24 | |
| 25 | // Convert input strings to arrays for easier manipulation |
| 26 | const board = input.map(row => row.split('')); |
| 27 | const result = Array(rows).fill().map(() => Array(cols).fill('')); |
| 28 | |
| 29 | // Directions for 8 adjacent cells (horizontal, vertical, diagonal) |
| 30 | const directions = [ |
| 31 | [-1, -1], [-1, 0], [-1, 1], |
| 32 | [0, -1], [0, 1], |
| 33 | [1, -1], [1, 0], [1, 1] |
| 34 | ]; |
| 35 | |
| 36 | for (let i = 0; i < rows; i++) { |
| 37 | for (let j = 0; j < cols; j++) { |
| 38 | // If current cell is a flower, keep it as is |
| 39 | if (board[i][j] === '*') { |
| 40 | result[i][j] = '*'; |
| 41 | } else { |
| 42 | // Count adjacent flowers |
| 43 | let count = 0; |
| 44 | |
| 45 | for (const [dx, dy] of directions) { |
| 46 | const ni = i + dx; |
| 47 | const nj = j + dy; |
| 48 | |
| 49 | // Check if the adjacent cell is within bounds |
| 50 | if (ni >= 0 && ni < rows && nj >= 0 && nj < cols) { |
| 51 | if (board[ni][nj] === '*') { |
| 52 | count++; |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | // Edge Case: No adjacent flowers - leave cell empty |
| 58 | if (count === 0) { |
| 59 | result[i][j] = ' '; |
| 60 | } else { |
| 61 | // Edge Case: Has adjacent flowers - show count |
| 62 | result[i][j] = count.toString(); |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | // Convert arrays back to strings |
| 69 | return result.map(row => row.join('')); |
| 12 | 70 | }; |
| 71 | |
| 72 | // Handled Edge Cases: Empty grid with no rows, grid with no columns, grid with all flowers, grid with no flowers, single cell grid, edge and corner cells with fewer neighbors |
| 73 | } |