| 8 | 8 | * @returns {number[][]} |
| 9 | 9 | */ |
| 10 | 10 | export const spiralMatrix = (size) => { |
| 11 | | throw new Error('Remove this line and implement the function'); |
| 11 | // Edge Case: size 0 or negative size |
| 12 | if (size <= 0) { |
| 13 | return []; |
| 14 | } |
| 15 | |
| 16 | // Edge Case: size 1 matrix |
| 17 | if (size === 1) { |
| 18 | return [[1]]; |
| 19 | } |
| 20 | |
| 21 | // Create an empty matrix filled with zeros |
| 22 | const matrix = Array(size).fill().map(() => Array(size).fill(0)); |
| 23 | |
| 24 | let counter = 1; |
| 25 | let startRow = 0; |
| 26 | let endRow = size - 1; |
| 27 | let startCol = 0; |
| 28 | let endCol = size - 1; |
| 29 | |
| 30 | while (startRow <= endRow && startCol <= endCol) { |
| 31 | // Top row: left to right |
| 32 | for (let i = startCol; i <= endCol; i++) { |
| 33 | matrix[startRow][i] = counter++; |
| 34 | } |
| 35 | startRow++; |
| 36 | |
| 37 | // Right column: top to bottom |
| 38 | for (let i = startRow; i <= endRow; i++) { |
| 39 | matrix[i][endCol] = counter++; |
| 40 | } |
| 41 | endCol--; |
| 42 | |
| 43 | // Bottom row: right to left (if there's still a row to fill) |
| 44 | if (startRow <= endRow) { |
| 45 | for (let i = endCol; i >= startCol; i--) { |
| 46 | matrix[endRow][i] = counter++; |
| 47 | } |
| 48 | endRow--; |
| 49 | } |
| 50 | |
| 51 | // Left column: bottom to top (if there's still a column to fill) |
| 52 | if (startCol <= endCol) { |
| 53 | for (let i = endRow; i >= startRow; i--) { |
| 54 | matrix[i][startCol] = counter++; |
| 55 | } |
| 56 | startCol++; |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | return matrix; |
| 12 | 61 | }; |
| 62 | |
| 63 | // Handled Edge Cases: size 0 or negative size, size 1 matrix |