59. Spiral Matrix II(js)
59. Spiral Matrix II
Given a positive integer n, generate a square matrix filled with elements from 1 to n2in spiral order.
Example:
Input: 3 Output: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
题意:给定数字n,返回nXn的数组,顺时针输出为从小到大
代码如下:
/** * @param {number} n * @return {number[][]} */ var generateMatrix = function(n) { var top=0,left=0; var bottom=n-1,right=n-1; var num=1; //创建一个二维数组 var res=[]; for(var i=0;i<n;i++){ res[i]=new Array(); for(var j=0;j<n;j++){ res[i][j]=0; } } //按照对应规则将数字填入数组 while(top<bottom && left<right){ //从左向右 for(var i=left;i<right;i++){ res[top][i]=num; num++; } //从上往下 for(var i=top;i<bottom;i++){ res[i][right]=num; num++; } //从右向左 for(var i=right;i>left;i--){ res[bottom][i]=num; num++; } //从下向上 for(var i=bottom;i>top;i--){ res[i][left]=num; num++; } left++; right--; bottom--; top++; } //当总项数为奇数时,会有一个落单的项,将那项存入数组 if(n%2===1){ var middle=parseInt(n/2); res[middle][middle]=n*n; } return res; };