#include<iostream>
#include<iomanip>
using namespace std;
int a[10][10];
int main(void)
{
// 输出 n*n 矩阵
// x,y控制行和列
// total用来计数
int n,x,y,total;
cin >> n;
memset(a,0,sizeof(a));
// 初始化(x,y)坐标为(0,0)
x = y = 0;
// 让左上角第一个数为1
total = a[0][0] = 1;
while (total < n * n)
{
// 往右走,行不变,列加1
// y + 1 < n是判断边界
// a[x][y + 1]是否已经填过数了
while ((y + 1 < n) && (!a[x][y + 1]))
{
a[x][++y] = ++total;
}
// 往下走,列不变,行加1
while ((x + 1 < n) && (!a[x+1][y]))
{
a[++x][y] = ++total;
}
// 往左走,行不变,列减1
while ((y - 1 >= 0) && (!a[x][y-1]))
{
a[x][--y] = ++total;
}
// 往上走,列不变,行减1
while ((x - 1 >= 0) && (!a[x-1][y]))
{
a[--x][y] = ++total;
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
// 位宽为3
cout << setw(3) << a[i][j] ;
}
cout << endl;
}
system("pause");
return 0;
}
二维数组---蛇形填数
最新推荐文章于 2023-11-06 22:29:48 发布