螺旋矩阵II
https://leetcode.cn/problems/spiral-matrix-ii/description/
循环不变量
每次循环处理的区间是有规律的
左闭右开
1 2 3 4 5 6
| o . . . 1 o 1 . . . . . . . . . . . . . . . . . . . . . . 1 o 1 . . . o
|
解题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| var generateMatrix = function(n) { let startx = 0, starty = 0; let end = n-1; count = 1; let matrix = new Array(n).fill(0).map(()=>new Array(n).fill(0)); while(Math.floor(n/2)){ for (let j=starty;j<end;j++){ matrix[startx][j] = count++; } for(let i = startx;i<end;i++){ matrix[i][end] = count++; } for(let j=end;j>starty;j--){ matrix[end][j] = count++; } for(let i=end;i>startx;i--){ matrix[i][starty] = count++; } end--; startx++; starty++; n-=2; } if (n) { matrix[startx][starty] = count; } return matrix; };
|