帮我用c++写一个螺旋矩阵的代码
时间: 2023-08-28 22:24:35 浏览: 95
以下是用 C++ 编写的螺旋矩阵生成程序:
```c++
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> matrix(n, vector<int>(n));
int num = 1, rowBegin = 0, rowEnd = n - 1, colBegin = 0, colEnd = n - 1;
while (rowBegin <= rowEnd && colBegin <= colEnd) {
// Traverse Right
for (int j = colBegin; j <= colEnd; j++) {
matrix[rowBegin][j] = num++;
}
rowBegin++;
// Traverse Down
for (int j = rowBegin; j <= rowEnd; j++) {
matrix[j][colEnd] = num++;
}
colEnd--;
// Traverse Left
if (rowBegin <= rowEnd) {
for (int j = colEnd; j >= colBegin; j--) {
matrix[rowEnd][j] = num++;
}
rowEnd--;
}
// Traverse Up
if (colBegin <= colEnd) {
for (int j = rowEnd; j >= rowBegin; j--) {
matrix[j][colBegin] = num++;
}
colBegin++;
}
}
return matrix;
}
int main() {
int n = 5;
vector<vector<int>> matrix = generateMatrix(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << matrix[i][j] << "\t";
}
cout << endl;
}
return 0;
}
```
该程序使用了一个二维 vector 来存储生成的矩阵,然后使用类似于蛇形遍历的方式依次填入数字,最终输出生成的矩阵。
阅读全文