59. Spiral Matrix II (Medium)

https://leetcode.com/problems/spiral-matrix-ii/

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

```Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
```

Solutions

``````class Solution {
int count = 1;

public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = 0;
}
}

if (n == 0) {
return matrix;
}

int width = matrix[0].length;

int m = Math.min(width, n);

for (int i = 0; i < (int) Math.ceil(m / 2.0); i++) {
generateMatrix(matrix, i);
}

return matrix;
}

private int[][] generateMatrix(int[][] matrix, int margin) {
int width = matrix[0].length;
int height = matrix.length;

if (margin > width || margin > height) {
return matrix;
}

for (int i = margin; i < width - margin; i++) {
matrix[margin][i] = count++;
}

for (int i = margin + 1; i < height - margin; i++) {
matrix[i][width - margin - 1] = count++;
}

for (int i = width - margin - 2; i >= margin && (height - margin - 1 > margin); i--) {
matrix[height - margin - 1][i] = count++;
}

for (int i = height - margin - 2; i > margin && (width - margin - 1 > margin); i--) {
matrix[i][margin] = count++;
}

return matrix;
}
}
``````