链接:
https://leetcode.com/problems/spiral-matrix-ii/
大意:
给定一个正整数n,要求返回一个二维矩阵nxn。其中矩阵的每个元素螺旋式递增产生。例子:
思路:
和之前的螺旋打印二维数组元素思路类似,这里就不再累述。螺旋打印二维数组:https://blog.csdn.net/smart_ferry/article/details/88843732
代码:
class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
helper(res, 0, n - 1, 1);
return res;
}
public void helper(int[][] res, int rowStart, int rowEnd, int val) {
if (rowStart > rowEnd)
return ;
if (rowStart == rowEnd) {
res[rowStart][rowEnd] = val;
return ;
}
int rs = rowStart, re = rowEnd, cs = rs, ce = re;
while (cs < ce) {
res[rs][cs++] = val++;
}
cs = rs;
while (rs < re) {
res[rs++][ce] = val++;
}
rs = cs;
while (ce > cs) {
res[re][ce--] = val++;
}
ce = re;
while (re > rs) {
res[re--][cs] = val++;
}
re = ce;
helper(res, rs + 1, re - 1, val);
}
}
结果:
结论:
思路都是现成的,只不过是换了个题。