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 ]]
public static int[][] generateMatrix(int n) {
if(n<0)
return null;
int[][] matrix=new int[n][n];
int x=0,y=0,i=1;
while(n>0){
if(n==1){
matrix[x][y]=i;
break;
}
for(int j=0;j<n-1;j++)
matrix[x][y++]=i++;
for(int j=0;j<n-1;j++)
matrix[x++][y]=i++;
for(int j=0;j<n-1;j++)
matrix[x][y--]=i++;
for(int j=0;j<n-1;j++)
matrix[x--][y]=i++;
x++;y++;
n-=2;
}
return matrix;
}