蛇形填数(矩阵)

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

}

相关推荐
Wang15301 小时前
c++与Java谁的性能更胜一筹
java·c++
Tipriest_1 小时前
C++ 中 std::move 的使用方法与注意事项
c++·move
yuuki2332331 小时前
【C++】vector底层实现全解析
c++·后端·算法
小尧嵌入式1 小时前
C++选择排序插入排序希尔排序快排归并排及大小根堆实现优先级队列
数据结构·c++·windows·算法·排序算法
Dream it possible!2 小时前
LeetCode 面试经典 150_分治_合并 K 个升序链表(108_23_C++_困难)
c++·leetcode·链表·面试·分治
天赐学c语言2 小时前
12.29 - 字符串相加 && vector和map的区别
数据结构·c++·算法·leecode
yuuki2332332 小时前
【C++】 list 实现:双向循环链表解析
c++·链表·list
随意起个昵称2 小时前
【做题总结】顺子(双指针)
c++·算法
郝学胜-神的一滴2 小时前
Linux多线程编程:深入解析pthread_detach函数
linux·服务器·开发语言·c++·程序人生
阿闽ooo2 小时前
深入浅出享元模式:从图形编辑器看对象复用的艺术
c++·设计模式·编辑器·享元模式