一、螺旋方阵 (20 分)
所谓“螺旋方阵”,是指对任意给定的N,将1到N×N的数字从左上角第1个格子开始,按顺时针螺旋方向顺序填入N×N的方阵里。本题要求构造这样的螺旋方阵。
输入格式:
输入在一行中给出一个正整数N(<10)。
输出格式:
输出N×N的螺旋方阵。每行N个数字,每个数字占3位。
输入样例:
5
输出样例:
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
原文链接:https://blog.youkuaiyun.com/Potestatem/article/details/115014187
思路:按照右下左上来模拟数字变化,引入数组存数字使数组不为空,表示已经标记过,不再询问。
#include <bits/stdc++.h>
using namespace std;
int a[20][20];
int main()
{
int n;
cin >> n;
int cnt = 1;
int x = 0, y = 0;
memset(a, 0, sizeof(a));
a[x][y] = 1;
while(cnt < n*n)
{
while(y + 1 < n && !a[x][y+1])
{
++y;
a[x][y] = ++cnt;
}
while(x + 1 < n && !a[x+1][y])
{
++x;
a[x][y] = ++cnt;
}
while(y - 1 >= 0 && !a[x][y-1])
{
--y;
a[x][y] = ++cnt;
}
while(x - 1 >= 0 && !a[x-1][y])
{
--x;
a[x][y] = ++cnt;
}
}
int i, j;
for(i = 0; i < n; i ++)
{
for(j = 0; j < n; j ++)
{
printf("%3d", a[i][j]);
}
cout << "\n";
}
return 0;
}
二、螺旋矩阵
#include <bits/stdc++.h>
using namespace std;
const int N = 20;
int a[N][N];
int main()
{
int n;
cin >> n;
memset(a, 0, sizeof(a));
a[0][0] = 1;
int tot = 1;
int x = 0, y = 0;
while(tot < n*n)
{
while(y + 1 < n && !a[x][y + 1]) a[x][++y] = ++tot;
++ x;
a[x][y] = ++ tot;
while(y - 1 >= 0 && !a[x][y - 1]) a[x][--y] = ++tot;
++ x;
a[x][y] = ++ tot;
}
for(x = 0; x < n; x ++)
{
for(y = 0; y < n; y ++)
{
printf("%4d", a[x][y]);
}
cout << endl;
}
}
三、蛇形矩阵
#include <bits/stdc++.h>
using namespace std;
int a[20][20];
int main()
{
int n;
cin >> n;
memset(a, 0, sizeof(a));
int num = 1;
int i, j;
for(i = 1; i <= n; i ++)
{
if(i&1)
{
for(j = 1; j <= i; j ++)
{
a[i + 1 - j][j] = num ++;
}
}
else
{
for(j = i; j >= 1; j --)
{
a[i + 1 - j][j] = num ++;
}
}
}
for(i = n + 1; i <= 2*n - 1; i ++)
{
if(i&1)
{
for(j = i - n + 1; j <= n; j ++)
{
a[i + 1 - j][j] = num ++;
}
}
else
{
for(j = n; j >= i - n + 1; j --)
{
a[i + 1 - j][j] = num ++;
}
}
}
for(i = 1; i <= n; i ++)
{
for(j = 1; j <= n; j ++)
{
printf("%4d", a[i][j]);
}
cout << "\n";
}
return 0;
}