Leetcode 59. Spiral Matrix II (Medium) (java)
Tag: Array
Difficulty: Medium
/*
59. Spiral Matrix II (Medium)
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
*/
public class Solution {
public int[][] generateMatrix(int n) {
if (n < 1) {
return new int[n][n];
}
int[][] res = new int[n][n];
int i = n - 1, j = n - 1, h = 0, l = 0, k = 0;
while (k < n * n) {
for (int col = l; col <= j; col++) {
res[h][col] = ++k;
}
if (++h > i) {
break;
}
for (int row = h; row <= i; row++) {
res[row][j] = ++k;
}
if (--j < l) {
break;
}
for (int col = j; col >= l; col--) {
res[i][col] = ++k;
}
if (--i < h) {
break;
}
for (int row = i; row >= h; row--) {
res[row][l] = ++k;
}
if (++l > j) {
break;
}
}
return res;
}
}