Leetcode算法Java全解答–59. 螺旋矩阵 II
题目
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
想法
每一层都是这个顺序(红绿蓝紫),数值虽然不对,但是思路是这样。
第一层循环
第一次:123345,
第二次:6789,
第三次:10 11 12 13
第四次:14 15 16
第二层循环
第一次:17 18 19
。。。
结果
// TODO
总结
// TODO
代码
我的答案
public class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int num=1, d=n-1, x=(n-d)/2, y=(n-d)/2;
while (d > 0) {
for(int i=0; i<d; i++) res[x][y+i] = num++; //①
y += d;
for(int i=0; i<d; i++) res[x+i][y] = num++; //②
x += d;
for(int i=0; i<d; i++) res[x][y-i] = num++; //③
y = (n-d) / 2;
for(int i=0; i<d; i++) res[x-i][y] = num++; //④
d -= 2;
x = (n-d) / 2;
y = (n-d) / 2;
}
if (d==0) res[x][y] = num; //⑤
return res;
}
}
大佬们的答案
class Solution {
public int[][] generateMatrix(int n) {
int[][] res =new int[n][n];
int t=1;
int a=0,b=0;
int i=0,j=0;
for(;i>=a&&i<n&&j>=b&&j<n;a++,b++,n--){
for(;j<n;j++)
res[i][j]=t++;
for(i++,j--;i<n;i++)
res[i][j]=t++;
for(i--,j--;j>=b&&i>a;j--)
res[i][j]=t++;
for(j++,i--;i>a&&j>=b;i--)
res[i][j]=t++;
i=a+1;
j=b+1;
}
return res;
}
}
测试用例
其他
代码托管码云地址:https://gitee.com/lizhaoandroid/LeetCodeAll.git
查看其他内容可以点击专栏或者我的博客哈:https://blog.csdn.net/cmqwan
“大佬们的答案” 标签来自leetcode,侵权请联系我进行删改
如有疑问请联系,联系方式:QQ3060507060