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