蛇形矩阵c++
时间: 2023-07-01 18:06:42 浏览: 50
以下是一个生成蛇形矩阵的C++代码示例:
```c++
#include <iostream>
using namespace std;
const int MAX_SIZE = 100;
int main() {
int n;
int a[MAX_SIZE][MAX_SIZE];
cout << "请输入一个正整数n:";
cin >> n;
// 初始化矩阵
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = 0;
}
}
// 填充矩阵
int num = 1; // 填充的数字
int i = 0, j = 0; // 当前位置
a[i][j] = num;
while (num < n * n) {
// 向右上填充
while (i - 1 >= 0 && j + 1 < n && a[i-1][j+1] == 0) {
a[--i][++j] = ++num;
}
// 向左下填充
while (i + 1 < n && j - 1 >= 0 && a[i+1][j-1] == 0) {
a[++i][--j] = ++num;
}
// 向右填充
while (j + 1 < n && a[i][j+1] == 0) {
a[i][++j] = ++num;
}
// 向下填充
while (i + 1 < n && a[i+1][j] == 0) {
a[++i][j] = ++num;
}
}
// 输出矩阵
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << a[i][j] << "\t";
}
cout << endl;
}
return 0;
}
```
该代码使用了一个三层嵌套的循环来填充矩阵,其中:
1. 外层循环用于填充数字,直到填充完毕(即num >= n * n)为止。
2. 第一个内层循环用于向右上填充数字,直到无法继续为止。
3. 第二个内层循环用于向左下填充数字,直到无法继续为止。
4. 第三个内层循环用于向右填充数字,直到无法继续为止。
5. 第四个内层循环用于向下填充数字,直到无法继续为止。
这样就可以生成一个蛇形矩阵了。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)