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 ]
]
/**
* Return an array of arrays.
* Note: The returned array must be malloced, assume caller calls free().
*/
int** generateMatrix(int n) {
int **Maxtrix;
Maxtrix=(int **)malloc(n*sizeof(int*));
for(int k=0;k<n;k++)
Maxtrix[k]=(int *)malloc(sizeof(int)*n);
int number = 1;
int top = 0;
int bottom = n-1;
int left = 0;
int right = n-1;
int i,j;
while(number<=n*n)
{
for(i=left;i<=right;i++)
Maxtrix[top][i]=number++;
top++;
for(i=top;i<=bottom;i++)
Maxtrix[i][right]=number++;
right--;
for(i=right;i>=left;i--)
Maxtrix[bottom][i]=number++;
bottom--;
for(i=bottom;i>=top;i--)
Maxtrix[i][left]=number++;
left++;
}
return Maxtrix;
}