思路:绕(n / 2)圈,采用左开右闭顺时针填数组的方式。
遇到的问题:输出数组本身没问题,但是输出就总是只有" ] "。
解决:看了代码随想录的写法,悟出来了:模板代码给的每个参数都是有用的!!
代码:
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** generateMatrix(int n, int* returnSize, int** returnColumnSizes){
//returnSize拿来干啥的?是用来告诉主函数要输出的数组有多少行的,不然不设置就只输出“]”
* returnSize = n;//用来记录输出数组有多少行
* returnColumnSizes = (int *)malloc(sizeof(int) * n);//这个也是有用的!!记录输出数组每行有多少列,这里先动态分配内存出n行
int num = 2;//num拿来记各个值,直到n^2
int** res = (int **)malloc(sizeof(int *) * n);//malloc一个输出数组
for(int i = 0; i < n; i ++){//给每个res[i]动态分配内存
res[i] = (int *)malloc(sizeof(int) * n);
(* returnColumnSizes)[i] = n;//每行多少列
}
int loop = n / 2;//loop是需要循环的圈数
res[0][0] = 1;
int x = 0;
int y = 0;
int distance = 2;//设置偏离值
//int right = n - 1;//每一圈y的临界值
while(loop){//当圈数不等于零时
while(y <= n - distance){//向右赋值
res[x][++ y] = num ++;
}
while(x <= n - distance){//向下赋值
res[++ x][y] = num ++;
}
while(y > distance - 2){//向左赋值
res[x][-- y] = num ++;
}
while(x > distance - 1){//向上赋值
res[-- x][y] = num ++;
}
distance ++;
loop --;
}
if(n % 2 && n != 1){//如果n为奇数时,需要往最中间填入一个数,若n = 1则跳过判断,不然输出数组[[2]],正确的是[[1]].
res[n / 2][n / 2] = num;
}
return res;
}