This time your job is to fill a sequence of N positive integers into a spiral matrix in non-increasing order. A spiral matrix is filled in from the first element at the upper-left corner, then move in a clockwise spiral. The matrix has m rows and n columns, where m and n satisfy the following: m×n must be equal to N; m≥n; and m−n is the minimum of all the possible values.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N. Then the next line contains N positive integers to be filled into the spiral matrix. All the numbers are no more than . The numbers in a line are separated by spaces.
Output Specification:
For each test case, output the resulting matrix in m lines, each contains n numbers. There must be exactly 1 space between two adjacent numbers, and no extra space at the end of each line.
Sample Input:
12
37 76 20 98 76 42 53 95 60 81 58 93
Sample Output:
98 95 93
42 37 81
53 20 76
58 60 76
Ω
输出一个数组的降序(顺时针) 旋转矩阵,要求 。
首先确定 ,从 开始往下枚举,找到的第一个N的因子即为 。然后每次顺时针遍历一圈给旋转矩阵赋值,由外向内深入,但需要注意的是有时一圈会退化成一条边,不要重复赋值,否则会越界访问原始数组。当然简单一点可以每次都检查一下idx是否越界。
🐎
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
int main()
{
int r, n, m;
cin >> r;
int seq[r];
for (auto &k: seq)
cin >> k;
sort(seq, seq + r, greater());
for (n = int(sqrt(r)); n > 1; --n)
if (r % n == 0) break;
m = r / n;
int mtx[m][n], l = -1, idx = -1;
while (++l < (n + 1) / 2)
{
for (int i = l; i < n - l; ++i)
mtx[l][i] = seq[++idx];
for (int i = l + 1; i < m - l; ++i)
mtx[i][n - l - 1] = seq[++idx];
for (int i = n - l - 2; i >= l; --i)
mtx[m - l - 1][i] = seq[++idx];
if (l != n / 2)
for (int i = m - l - 2; i > l; --i)
mtx[i][l] = seq[++idx];
}
for (int i = 0; i < m; ++i)
{
printf("%d", mtx[i][0]);
for (int j = 1; j < n; ++j)
printf(" %d", mtx[i][j]);
printf("\n");
}
}
之所以只对竖边检查即可(if (l != n / 2)
)是因为
,因此只可能退化为一个点(
)或是一条竖边(
),而不会出现退化横边。而退化成一个点时,后两者for循环都不会进入,因此仅考虑竖边即可。嫌麻烦就每次都检查idx是否越界。