蛇形填数(矩阵)

#include <bits/stdc++.h>

using namespace std;

int main() {

int a[10][10] = {0};

int n;

cin >> n;

int num = 1;

int bot = n - 1;

int top = 0;

int left = 0;

int right = n - 1;

while (n * n >= num) {

for (int i = top; i <= bot; i++) {

a[i][right] = num++;

}

right--;

if (top <= bot) {

for (int j = right; j >= left; j--) {

a[bot][j] = num++;

}

bot--;

}

if (right >= left) {

for (int i = bot; i >= top; i--) {

a[i][left] = num++;

}

left++;

}

for (int j = left; j <= right; j++) {

a[top][j] = num++;

}

top++;

}

for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {

cout << setw(4) << a[i][j];

}

cout << endl;

}

return 0;

}

相关推荐
雾岛听蓝12 分钟前
C++11新特性(lambda、包装器)
c++·经验分享·笔记
散峰而望1 小时前
C++ 启程:从历史到实战,揭开命名空间的神秘面纱
c语言·开发语言·数据结构·c++·算法·github·visual studio
PingdiGuo_guo2 小时前
C++数据类型、变量常量
开发语言·c++
水饺编程2 小时前
第4章,[标签 Win32] :TextOut 测试案例3代码改编
c语言·c++·windows·visual studio
Darkwanderor2 小时前
数据结构 - 并查集的应用
数据结构·c++·并查集
多恩Stone3 小时前
【C++ debug】在 VS Code 中无 Attach 调试 Python 调用的 C++ 扩展
开发语言·c++·python
PingdiGuo_guo3 小时前
C++联合体详解!
开发语言·c++
浅念-3 小时前
C++ 继承
开发语言·c++·经验分享·笔记·学习·算法·继承
王老师青少年编程4 小时前
csp信奥赛C++之反素数
数据结构·c++·数学·算法·csp·信奥赛·反素数
YxVoyager5 小时前
基于 X-Macro 宏的手动 RTTI 实现模式
c++