力扣 C语言 螺旋矩阵
时间: 2025-01-24 07:56:20 AIGC 浏览: 57
### C语言实现螺旋矩阵
对于给定的矩阵,按照顺时针方向打印其元素可以采用模拟的方法。具体来说,在遍历过程中维护四个边界变量来控制访问范围,并随着每次边界的收缩调整这些变量。
```c
#include <stdio.h>
void spiralOrder(int** matrix, int matrixSize, int* matrixColSize) {
if (matrixSize == 0 || *matrixColSize == 0) return;
int top = 0;
int bottom = matrixSize - 1;
int left = 0;
int right = *matrixColSize - 1;
while (top <= bottom && left <= right) {
// Traverse from left to right along the top row.
for (int col = left; col <= right; ++col) {
printf("%d ", matrix[top][col]);
}
top++;
// Traverse downwards along the right column.
for (int row = top; row <= bottom; ++row) {
printf("%d ", matrix[row][right]);
}
right--;
if (top <= bottom) {
// Traverse from right to left along the bottom row.
for (int col = right; col >= left; --col) {
printf("%d ", matrix[bottom][col]);
}
bottom--;
}
if (left <= right) {
// Traverse upwards along the left column.
for (int row = bottom; row >= top; --row) {
printf("%d ", matrix[row][left]);
}
left++;
}
}
}
```
此函数接收一个二维整数数组`matrix`作为输入参数以及两个辅助参数用于指定该数组的实际尺寸。通过循环迭代的方式依次处理每一层直到所有的元素都被访问过为止[^2]。
阅读全文
相关推荐



















