给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
解题思路:这个题与LeetCode-54.螺旋矩阵(博客:https://blog.csdn.net/weixin_38823568/article/details/81740369)类似,不同点在于,用变量cnt = 1计数,然后按照54.螺旋矩阵的顺序遍历数组,遍历到的当前位置赋值为cnt
java代码:
class Solution {
public int[][] generateMatrix(int n) {
if(0 == n)
return new int[][] {};
int linemin = 1, linemax = n, colmin = 0, colmax = n, cnt = 1;
int[][] res = new int[n][n];
for(int i = 0; i < linemax; i++){
for(int j = colmin; j < colmax; j++){
res[i][j] = cnt++;
if(j == colmax-1){
colmax--;
for(int m = linemin; m < linemax; m++){
res[m][j] = cnt++;
if(m == linemax-1){
linemax--;
for(int o = colmax-1; o >= colmin; o--){
res[m][o] = cnt++;
if(o == colmin){
colmin++;
for(int p = linemax-1; p >= linemin; p--){
res[p][o] = cnt++;
if (p == linemin) {
linemin++;
break;
}
}
}
}
}
}
}
}
}
return res;
}
}