【数组】Spiral Matrix II
题目:
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 ] ]
思路:
本质上和上一题是一样的,这里我们要用数字螺旋的去填充矩阵。同理,我们也是逐个环的填充,每个环顺时针逐条边填充
/** * @param {number} n * @return {number[][]} */ var generateMatrix = function(n) { if(n==0){ return []; } var matrix=[]; for(var j=0;j<n;j++){ matrix[j]=[]; } var circle=Math.ceil(n/2); var a=n,val=1; for(var i=0;i<circle;i++,a-=2){ for(var col=i;col<i+a;col++){ matrix[i][col]=val++; } for(var row=i+1;row<i+a;row++){ matrix[row][i+a-1]=val++; } for(var col=i+a-2;col>=i;col--){ matrix[i+a-1][col]=val++; } for(var row=i+a-2;row>i;row--){ matrix[row][i]=val++; } } return matrix; };