# 59. Spiral Matrix II

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]


## 代码：

JavaScript代码：

/**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function(n) {
var number=[];
for(var i=0;i<n;i++)
number.push([]);
var top=0,left=0,down=n-1,right=n-1,k=1;
while(top<=down)
{
for(var i=left;i<=right;i++)
number[top][i]=k++;
top++;
for(var i=top;i<=down;i++)
number[i][right]=k++;
right--;
for(var i=right;i>=left;i--)
number[down][i]=k++;
down--;
for(var i=down;i>=top;i--)
number[i][left]=k++;
left++;
}
return number;
};

Java代码：

class Solution {
public int[][] generateMatrix(int n) {
if(n==0)
return null;
int [][]spiral=new int[n][n];
int k=0;
int left=0,top=0,down=n-1,right=n-1;
while(top<=down)
{
for(int i=left;i<=right;i++)
spiral[top][i]=++k;
top++;
for(int j=top;j<=down;j++)
spiral[j][right]=++k;
right--;
for(int i=right;i>=left;i--)
spiral[down][i]=++k;
down--;
for(int j=down;j>=top;j--)
spiral[j][left]=++k;
left++;
}
return spiral;
}
}

bwcxljsm