问题描述
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 int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int left = 0, right = n - 1, bottom = n - 1, top = 0, num = 1;
while (left < right && top < bottom) {
for (int i = left; i < right; i++) {
res[top][i] = num++;
}
for (int i = top; i < bottom; i++) {
res[i][right] = num++;
}
for (int i = right; i > left; i--) {
res[bottom][i] = num++;
}
for (int i = bottom; i > top; i--) {
res[i][left] = num++;
}
top++;
bottom--;
left++;
right--;
}
if (n % 2 == 1) {
res[n / 2][n / 2] = num;
}
return res;
}
网友评论