c语言给定一个m x n大小的整数矩阵(m行,n列),按顺时针螺旋的顺序打印矩阵中的所有
时间: 2024-06-13 09:06:48 浏览: 182
以下是C语言实现按顺时针螺旋顺序打印矩阵的代码:
```c
#include <stdio.h>
void spiralOrder(int matrix[][n], int m, int n) {
int rowBegin = 0, rowEnd = m - 1;
int colBegin = 0, colEnd = n - 1;
while (rowBegin <= rowEnd && colBegin <= colEnd) {
for (int i = colBegin; i <= colEnd; i++) {
printf("%d ", matrix[rowBegin][i]);
}
rowBegin++;
for (int i = rowBegin; i <= rowEnd; i++) {
printf("%d ", matrix[i][colEnd]);
}
colEnd--;
if (rowBegin <= rowEnd) {
for (int i = colEnd; i >= colBegin; i--) {
printf("%d ", matrix[rowEnd][i]);
}
rowEnd--;
}
if (colBegin <= colEnd) {
for (int i = rowEnd; i >= rowBegin; i--) {
printf("%d ", matrix[i][colBegin]);
}
colBegin++;
}
}
}
int main() {
int m, n;
scanf("%d %d", &m, &n);
int matrix[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}
spiralOrder(matrix, m, n);
return 0;
}
```
阅读全文