/** * 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) { //初始化二级指针和内存分配 int **result = (int **)malloc(n * sizeof(int *)); *returnSize = n; //返回列的大小初始化和内存分配 *returnColumnSizes = (int*)malloc(sizeof(int)*n); //返回二级指针各行内存分配和列的大小赋值 for (int i = 0; i < n; i++) { result[i] = (int *)malloc(n * sizeof(int)); returnColumnSizes[0][i] = n; } //数据边界初始化 int upper = 0; int down = n - 1; int left = 0; int right = n - 1;
int count = 1, target = n * n;
while(count <= target) { for(int i = left; i <= right; ++i) //数组向右移动 { result[upper][i] = count++; }
++upper; //重新设定上边
for(int i = upper; i <= down; ++i) //数组向下移动 { result[i][right] = count++; }
--right; //重新设定右边
for(int i = right; i >= left; --i) //数组向左移动 { result[down][i] = count++; }
--down; //重新设定下边界
for(int i = down; i >= upper; --i) //数组向上移动 { result[i][left] = count++; }