蛇形填数(矩阵)

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

}

相关推荐
澈2071 小时前
深入浅出C++滑动窗口算法:原理、实现与实战应用详解
数据结构·c++·算法
A.A呐1 小时前
【C++第二十九章】IO流
开发语言·c++
ambition202422 小时前
从暴力搜索到理论最优:一道任务调度问题的完整算法演进历程
c语言·数据结构·c++·算法·贪心算法·深度优先
kebeiovo2 小时前
atomic原子操作实现无锁队列
服务器·c++
Yungoal2 小时前
常见 时间复杂度计算
c++·算法
6Hzlia2 小时前
【Hot 100 刷题计划】 LeetCode 48. 旋转图像 | C++ 矩阵变换题解
c++·leetcode·矩阵
Ricky_Theseus3 小时前
C++右值引用
java·开发语言·c++
吴梓穆4 小时前
UE5 c++ 常用方法
java·c++·ue5
云栖梦泽4 小时前
Linux内核与驱动:9.Linux 驱动 API 封装
linux·c++
Morwit4 小时前
【力扣hot100】 1. 两数之和
数据结构·c++·算法·leetcode·职场和发展