/**
* Return an array of arrays.
* Note: The returned array must be malloced, assume caller calls free().
*/
int** generateMatrix(int n) {
int x0 = 0; // top left x
int y0 = 0; // top left y
int count = 0;
int i = 0;
int *vector = (int*)malloc(sizeof(int) * n * n);
for(i=0; i<n*n; i++){
vector[i] = i + 1;
}
int **matrix = (int**) malloc(sizeof(int*) * n);
for(i=0; i<n; i++){
matrix[i] = (int*)malloc(sizeof(int) * n);
}
if( 0 == n ){
return NULL;
}
if( 1 == n ){
matrix[0][0] = 1;
return matrix;
}
// loop
while( n >= 1){
int x1 = x0 + n - 1; // bottom right x
int y1 = y0 + n - 1; // bottom right y
// first row
for(i=y0; i<=y1; i++){
matrix[x0][i] = vector[count++];
}
// last col
for(i=x0+1; i<=x1; i++){
matrix[i][y1] = vector[count++];
}
// last row
if(n > 1){ // matrix need to be at least two rows
for(i=y1-1; i>=y0; i--){
matrix[x1][i] = vector[count++];
}
}
// first col
if(n > 1){ // matrix need to be at least two cols
for(i=x1-1; i>=x0+1; i--){
matrix[i][y0] = vector[count++] ;
}
}
x0++;
y0++;
n-=2;
}
return matrix;
}
spiralMatrixII
最新推荐文章于 2022-03-18 21:32:08 发布