MicroChip TCPIP协议栈移植指南:单片机以太网联网实战
2026/9/7 9:56:59
LeetCode 54. 螺旋矩阵,C 语言实现。
维护四个边界变量,按顺时针逐层收缩遍历,将结果存入动态分配的数组中。
/** * Note: The returned array must be malloced, assume caller calls free(). */int*spiralOrder(int**matrix,intmatrixSize,int*matrixColSize,int*returnSize){if(matrixSize==0||matrixColSize[0]==0){*returnSize=0;returnNULL;}intm=matrixSize;intn=matrixColSize[0];inttotal=m*n;int*result=(int*)malloc(total*sizeof(int));*returnSize=total;inttop=0,bottom=m-1;intleft=0,right=n-1;intidx=0;while(top<=bottom&&left<=right){// 1. 从左到右遍历 top 行for(intcol=left;col<=right;col++){result[idx++]=matrix[top][col];}top++;// 2. 从上到下遍历 right 列for(introw=top;row<=bottom;row++){result[idx++]=matrix[row][right];}right--;// 3. 从右到左遍历 bottom 行(需检查是否还有行)if(top<=bottom){for(intcol=right;col>=left;col--){result[idx++]=matrix[bottom][col];}bottom--;}// 4. 从下到上遍历 left 列(需检查是否还有列)if(left<=right){for(introw=bottom;row>=top;row--){result[idx++]=matrix[row][left];}left++;}}returnresult;}free)| 要点 | 说明 |
|---|---|
| 动态分配 | malloc(total * sizeof(int)),调用方负责free |
returnSize | 必须设置,LeetCode 通过它知道返回数组长度 |
| 空矩阵处理 | matrixSize == 0时返回NULL,returnSize = 0 |
| 边界检查 | 步骤 3 和 4 的if防止单行/单列时重复遍历 |
| 索引递增 | 用idx++依次填充结果数组 |