蛇形填数(矩阵)

#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 分钟前
【C++入门】Cyber深度漫游者的初始链路——【类与对象】初始化成员列表
开发语言·c++·dubbo·类与对象·初始化成员列表
mmz120712 分钟前
逆序对问题(c++)
c++·算法
化学在逃硬闯CS13 分钟前
Leetcode110.平衡二叉树
数据结构·c++·算法·leetcode
谢铭轩14 分钟前
题解:P8035 [COCI 2015/2016 #7] Otpor
c++·算法
阿猿收手吧!22 分钟前
【C++】模块:告别头文件新时代
开发语言·c++
星火开发设计26 分钟前
虚析构函数:解决子类对象的内存泄漏
java·开发语言·前端·c++·学习·算法·知识
闻缺陷则喜何志丹34 分钟前
【拆位法】P9277 [AGM 2023 资格赛] 反转|普及+
c++·算法·位运算·拆位法
maplewen.36 分钟前
C++ 多态原理深入理解
开发语言·c++·面试
tbRNA1 小时前
C++ string类
开发语言·c++
ccLianLian1 小时前
算法基础·C++常用操作
开发语言·数据结构·c++