C语言二维数组顺时钟遍历
时间: 2023-10-14 17:14:01 浏览: 87
二维数组遍历
二维数组顺时针遍历可以使用模拟的方式,设置四个变量来控制遍历方向和位置。
以下是一个示例代码:
```c
#include <stdio.h>
#define ROW 3
#define COL 4
void clockwise_traversal(int arr[][COL], int row, int col) {
int left = 0, right = col - 1;
int top = 0, bottom = row - 1;
while (left <= right && top <= bottom) {
// 从左往右
for (int i = left; i <= right; i++) {
printf("%d ", arr[top][i]);
}
top++;
// 从上往下
for (int i = top; i <= bottom; i++) {
printf("%d ", arr[i][right]);
}
right--;
// 从右往左
if (top <= bottom) {
for (int i = right; i >= left; i--) {
printf("%d ", arr[bottom][i]);
}
bottom--;
}
// 从下往上
if (left <= right) {
for (int i = bottom; i >= top; i--) {
printf("%d ", arr[i][left]);
}
left++;
}
}
}
int main() {
int arr[ROW][COL] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
};
clockwise_traversal(arr, ROW, COL);
return 0;
}
```
输出结果为:
```
1 2 3 4 8 12 11 10 9 5 6 7
```
阅读全文