蛇形填数 C++代码
时间: 2024-11-01 22:05:38 浏览: 26
信息奥赛课课通(C++)p179-例3蛇形方阵
蛇形填数,也被称为帕斯卡三角形(Pascal's Triangle),是一个经典的数学图形,每一行都是前一行的两倍加当前行数减一。在C++中,我们可以使用动态规划的方式来生成它。下面是一个简单的C++代码示例:
```cpp
#include<iostream>
using namespace std;
vector<vector<int>> generateSpiral(int n) {
vector<vector<int>> pascal(n, vector<int>(n, 0));
for (int i = 0; i < n; ++i) {
pascal[i][0] = pascal[i][i] = 1;
}
int top = 0, bottom = n - 1, left = 0, right = n - 1;
while (top <= bottom && left <= right) {
// Fill the current row from left to right
for (int i = left; i <= right; ++i) {
pascal[top][i] = pascal[top][i - 1] + pascal[top + 1][i];
}
top++;
// Fill the current column from top to bottom
for (int i = top; i <= bottom; ++i) {
pascal[i][right] = pascal[i - 1][right] + pascal[i][right - 1];
}
right--;
// If there are remaining elements at the bottom row, fill them
if (top <= bottom) {
for (int i = right; i >= left; --i) {
pascal[bottom][i] = pascal[bottom][i + 1] + pascal[bottom - 1][i];
}
bottom--;
}
// If there are remaining elements at the rightmost column, fill them
if (left <= right) {
for (int i = bottom; i >= top; --i) {
pascal[i][left] = pascal[i + 1][left] + pascal[i][left - 1];
}
left++;
}
}
return pascal;
}
int main() {
int n = 5;
vector<vector<int>> spiralTriangle = generateSpiral(n);
for (const auto& row : spiralTriangle) {
for (int num : row) {
cout << num << " ";
}
cout << "\n";
}
return 0;
}
```
上述代码首先初始化一个二维向量`pascal`,并设置边界条件。接着在一个循环中处理每一层的填充,按照左->右,上->下,右->上,下->左的顺序。通过这种方式,我们能够生成帕斯卡三角形的每一层,并存储在`pascal`矩阵中。
阅读全文