
LeetCode 59. 螺旋矩阵 II 的 C 语言实现如下。实现思路使用边界收缩法维护四个边界 top、bottom、left、right按照“从左到右 → 从上到下 → 从右到左 → 从下到上”的顺序依次填充数字。每完成一条边对应的边界向内收缩一格。循环条件 num n * n 保证每个位置只被填充一次适用于奇数和偶数 n。C 语言代码/** * 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(intn,int*returnSize,int**returnColumnSizes){*returnSizen;*returnColumnSizes(int*)malloc(n*sizeof(int));int**matrix(int**)malloc(n*sizeof(int*));for(inti0;in;i){matrix[i](int*)malloc(n*sizeof(int));(*returnColumnSizes)[i]n;}inttop0,bottomn-1;intleft0,rightn-1;intnum1;while(numn*n){// 1. 上边从左到右for(intcolleft;colrightnumn*n;col){matrix[top][col]num;}top;// 2. 右边从上到下for(introwtop;rowbottomnumn*n;row){matrix[row][right]num;}right--;// 3. 下边从右到左for(intcolright;colleftnumn*n;col--){matrix[bottom][col]num;}bottom--;// 4. 左边从下到上for(introwbottom;rowtopnumn*n;row--){matrix[row][left]num;}left;}returnmatrix;}复杂度分析· 时间复杂度O(n²)每个元素恰好被访问并赋值一次。· 空间复杂度O(1)不计入必须返回的矩阵空间仅使用了常数个变量。说明· 代码中每个 for 循环都加入了 num n * n 的判断可以避免当 n 为奇数时最内层只有一个元素被重复填充的问题。· 注意正确设置 *returnSize 和 *returnColumnSizesLeetCode 会通过这两个参数获取矩阵的行数和每行的列数。