蛇形方阵顺时针输出c++
时间: 2024-01-27 17:12:50 浏览: 111
以下是蛇形方阵顺时针输出的C++代码:
```
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int arr[n][n];
int num = 1;
int row_start = 0, row_end = n - 1, col_start = 0, col_end = n - 1;
while (row_start <= row_end && col_start <= col_end) {
for (int i = col_start; i <= col_end; i++) {
arr[row_start][i] = num++;
}
row_start++;
for (int i = row_start; i <= row_end; i++) {
arr[i][col_end] = num++;
}
col_end--;
for (int i = col_end; i >= col_start; i--) {
arr[row_end][i] = num++;
}
row_end--;
for (int i = row_end; i >= row_start; i--) {
arr[i][col_start] = num++;
}
col_start++;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
阅读全文