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−nis 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 104. 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
---------------------------------------这是题目和解题的分割线---------------------------------------
哇好久没见过顺时针打印矩阵的题了,上一次还是大一的时候,那会儿觉得好难啊哈哈哈。
思路大概是这样:真正顺时针打印是不可能的,毕竟都输出后边的位置了怎么可能回到前边来,所以需要模拟这个过程的同时找一个二维数组来记录下标。简单点看,其实就是四个方向,右、下、左、上。只不过要重复多少次的问题(外部循环)。这里可以用遍历一维数组的计数器cnt(或者随便什么名字)的取值作为终止条件(当cnt自增/自减的次数==n时,说明该数组遍历完毕,循环中止)。而四个方向(内部循环)可以用四个循环来实现。具体的还是看代码吧~不明白的话可以试着注释其他三个循环的代码来观察剩下那个循环的输出~
还有就是测试点的问题。可能全网只有我最后一个测试点出现过段错误吧QAQ,一时傻了把10^4误以为是1000,导致数组开太小了。还有一开始的第四个测试点浮点错误,捉虫了半天,才发现是我的代码在n=1时不会有输出,所以说特殊值的输入一定要多加小心啊~~~如果多个测试点答案错误的话,检查一下内部循环有没有加上对数组遍历是否完毕的判断啊。
#include<cstdio>
#include<algorithm>
const int maxN = 10010;
using namespace std;
int newA[maxN][maxN];
int main()
{
int n,i,j,a[maxN];
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,a+n);
//row是行,col是列
int row,col,minN = 10010;
//我下面的循环代码将n=1排除在外,所以就单独写一个if语句来输出吧
if(n==1)
{
printf("%d\n",a[0]);
return 0;
}
//寻找差值最小的乘积数
for(i=1;i<=n/2;i++)
{
if(n%i==0&&abs(n/i-i)<minN)
{
minN = abs(n/i-i);
col = i;
}
}
row = n/col;
//sort默认从小到大输出,但题目要求从大到小,所以倒着遍历
int cnt = n-1;
//cnt<0时数组遍历完毕,结束外层循环
//内部循环也别忘了加上cnt>=0的判断,毕竟随时可能遍历完毕~
for(i=0;cnt>=0;i++)
{
//右方向,比如第一遍循环时输出的是 98 95 93
for(j=i;j<col-i&&cnt>=0;j++)
newA[i][j] = a[cnt--];
//下方向
for(j=i+1;j<row-i-1&&cnt>=0;j++)
newA[j][col-i-1] = a[cnt--];
//左方向
for(j=col-i-1;j>i&&cnt>=0;j--)
newA[row-i-1][j] = a[cnt--];
//上方向
for(j=row-i-1;j>i&&cnt>=0;j--)
newA[j][i] = a[cnt--];
}
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d",newA[i][j]);
if(j!=col-1) printf(" "); //末尾无空格
}
printf("\n");
}
return 0;
}