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]]
1 /**2 * Return an array of arrays.3 * Note:the returned array must is malloced, assume caller calls free ().4 */5 int* * Generatematrix (intN) {6 int**Maxtrix;7 8Maxtrix= (int**)malloc(nsizeof(int*));9 for(intk=0; k<n;k++)TenMaxtrix[k]= (int*)malloc(sizeof(int)*n); One A intNumber =1; - inttop =0; - intBottom = n1; the intleft =0; - intright = N1; - - inti,j; + while(number<=n*N) - { + for(i=left;i<=right;i++) Amaxtrix[top][i]=number++; attop++; - - for(i=top;i<=bottom;i++) -maxtrix[i][right]=number++; -right--; - in for(i=right;i>=left;i--) -maxtrix[bottom][i]=number++; tobottom--; + - for(i=bottom;i>=top;i--) themaxtrix[i][left]=number++; *left++; $ Panax Notoginseng } - returnMaxtrix; the}
Leecode-spiral Matrix II