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 ]
]
idea:
public int[][] generateMatrix(int n) {
//获得总数
int total = n * n;
//确定边界:上下左右
int u = 0, d = n - 1, l = 0, r = n - 1;
int i = 1;
int[][] ints = new int[n][n];
while (i <= total) {
//左到右
for (int j = l; j <= r; j++) {
ints[l][j] = i++;
}
u++;
//上到下
for (int j = u; j <= d; j++) {
ints[j][r] = i++;
}
r--;
//右到左
for (int j = r; j >= l; j--) {
ints[d][j] = i++;
}
d--;
//下到上
for (int j = d; j >= u; j--) {
ints[j][l] = i++;
}
l++;
}
return ints;
}