蛇形矩阵c++语言怎么写
时间: 2024-12-15 22:11:41 浏览: 14
蛇形矩阵,也被称为Z型矩阵或者Spiral Matrix,是一种特殊的二维数组填充方式,从左上角开始,沿着对角线向右下方螺旋移动。在C++中,可以采用迭代的方式来构造这种矩阵。下面是一个简单的例子:
```cpp
#include <iostream>
#include <vector>
// Function to generate a spiral matrix of given size
std::vector<std::vector<int>>& generateSpiral(int n) {
std::vector<std::vector<int>> spiral(n, std::vector<int>(n, 0));
int top = 0, bottom = n - 1, left = 0, right = n - 1;
int num = 1;
while (top <= bottom && left <= right) {
// Fill the first row from left to right
for (int i = left; i <= right; ++i) {
spiral[top][i] = num++;
}
top++;
// Fill the last column from top to bottom
for (int i = top; i <= bottom; ++i) {
spiral[i][right] = num++;
}
right--;
// Fill the last row from right to left
if (top <= bottom) {
for (int i = right; i >= left; --i) {
spiral[bottom][i] = num++;
}
bottom--;
}
// Fill the first column from bottom to top
if (left <= right) {
for (int i = bottom; i >= top; --i) {
spiral[i][left] = num++;
}
left++;
}
}
return spiral;
}
// Print the matrix
void printMatrix(const std::vector<std::vector<int>>& spiral) {
for (const auto& row : spiral) {
for (int num : row) {
std::cout << num << " ";
}
std::cout << "\n";
}
}
int main() {
int n = 5;
std::vector<std::vector<int>>& spiral_matrix = generateSpiral(n);
printMatrix(spiral_matrix);
return 0;
}
```
在这个程序中,`generateSpiral`函数生成了指定大小的蛇形矩阵,然后`printMatrix`用于打印矩阵内容。运行这个程序会得到一个5x5的蛇形矩阵。
阅读全文