蛇形填数(矩阵)

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

}

相关推荐
感哥4 小时前
C++ 面向对象
c++
沐怡旸5 小时前
【底层机制】std::shared_ptr解决的痛点?是什么?如何实现?如何正确用?
c++·面试
感哥12 小时前
C++ STL 常用算法
c++
saltymilk1 天前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥1 天前
C++ lambda 匿名函数
c++
沐怡旸1 天前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥1 天前
C++ 内存管理
c++
博笙困了1 天前
AcWing学习——双指针算法
c++·算法
感哥1 天前
C++ 指针和引用
c++
感哥2 天前
C++ 多态
c++