给你一个N行N列的方格矩阵,从外圈按顺时针依次填写自然数,这会构成一个螺旋阵,你能编程实现吗?用c++
时间: 2024-03-15 10:44:42 浏览: 70
当然可以,下面是一个C++实现的代码:
```c++
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> generate_spiral_matrix(int n) {
vector<vector<int>> matrix(n, vector<int>(n, 0));
int num = 1;
for (int layer = 0; layer < (n + 1) / 2; layer++) {
// 上边界
for (int i = layer; i < n - layer; i++) {
matrix[layer][i] = num;
num++;
}
// 右边界
for (int i = layer + 1; i < n - layer; i++) {
matrix[i][n - layer - 1] = num;
num++;
}
// 下边界
for (int i = layer + 1; i < n - layer; i++) {
matrix[n - layer - 1][n - i - 1 + layer] = num;
num++;
}
// 左边界
for (int i = layer + 1; i < n - layer - 1; i++) {
matrix[n - i - 1 + layer][layer] = num;
num++;
}
}
return matrix;
}
int main() {
int n = 5;
vector<vector<int>> matrix = generate_spiral_matrix(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
该程序同样采用了模拟的方式,按照顺时针方向依次填写自然数,最终生成一个螺旋矩阵。需要注意的是,在C++中,我们需要使用vector来表示二维数组。
阅读全文
相关推荐















