蛇形填数(矩阵)

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

}

相关推荐
布丁写代码1 小时前
GESP C++ 一级 2025年09月真题解析
开发语言·c++·程序人生·学习方法
喵个咪3 小时前
Qt 优雅实现线程安全单例模式(模板化 + 自动清理)
c++·后端·qt
欧阳x天3 小时前
C++入门(一)
c++
小张成长计划..3 小时前
【C++】:priority_queue的理解,使用和模拟实现
c++
Dream it possible!3 小时前
LeetCode 面试经典 150_二叉树层次遍历_二叉树的层平均值(82_637_C++_简单)
c++·leetcode·面试·二叉树
云泽8084 小时前
C++ List 容器详解:迭代器失效、排序与高效操作
开发语言·c++·list
xlq223224 小时前
15.list(上)
数据结构·c++·list
Elias不吃糖4 小时前
总结我的小项目里现在用到的Redis
c++·redis·学习
AA陈超5 小时前
使用UnrealEngine引擎,实现鼠标点击移动
c++·笔记·学习·ue5·虚幻引擎
No0d1es6 小时前
电子学会青少年软件编程(C/C++)六级等级考试真题试卷(2025年9月)
c语言·c++·算法·青少年编程·图形化编程·六级