蛇形填数(矩阵)

#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;

}

相关推荐
_风华ts28 分钟前
C++ 函数封装与绑定
c++·函数指针·函数封装
ShineWinsu42 分钟前
对于C++中stack和queue的详细介绍
开发语言·数据结构·c++·面试·stl·queue·stack
L_Aria1 小时前
6421. 【NOIP2019模拟11.11】匹配
c++·算法·动态规划
智者知已应修善业2 小时前
【PAT乙级真题解惑1012数字分类】2025-3-29
c语言·c++·经验分享·笔记·算法
-To be number.wan2 小时前
算法学习日记 | 双指针
c++·学习·算法
wangluoqi3 小时前
c++ 逆元 小总结
开发语言·c++
瓦特what?3 小时前
插 入 排 序
开发语言·c++
『往事』&白驹过隙;3 小时前
C/C++中的格式化输出与输入snprintf&sscanf
linux·c语言·c++·笔记·学习·iot·系统调用
Je1lyfish3 小时前
CMU15-445 (2026 Spring) Project#1 - Buffer Pool Manager
linux·数据库·c++·后端·链表·课程设计·数据库架构
zyeyeye3 小时前
自定义类型:结构体
c语言·开发语言·数据结构·c++·算法