1105 Spiral Matrix (25分)
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 10
4
. 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
测试点 3 4 5都是N=1 2 3的情况,自己输出一下测试试试
然后思路嘛,关键就是实现回旋地在矩阵赋值
按照下面的图来
首先确定了行数为row, 列数为clolumn
旋转的第一圈了黑色标记的1 2 3 4 旋转的第二圈填充了5 6 7 。
填充也就四种形式,先上 然后右 然后下 然后左 就是一圈了。
首先看填充四种形式第一种: 上方的填充,即第一圈 黑色1 和 第二圈的黑色5, 他们都是一个循环填充的,我们找找规则,如果以time表示第几圈,那么就是 for(int n=time; n<column-time; n++) 赋值是matrix[time][n]=sn[pos++];
同理四种填充的第二种:右侧填充,即第一圈的黑色2 和第二圈的黑色 6 ,
找找规则就是
for(int n=time+1; n<row-time; n++)
{
matrix[n][column-1-time]=sn[pos++];
}
同理剩下的也可找到规则
AC代码
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <vector>
#include <math.h>
using namespace std;
int cmp(int a,int b)
{
return a>b;
}
int main(void)
{
int N;
cin>>N;
int row,column;
if(N==1)
{
row=1;
column=1;
}
else if(N==2)
{
row=2;
column=1;
}
else if(N==3)
{
row=3;
column=1;
}
else
for(int i=sqrt(N); i>=1; i--)
{
if(N%i==0)
{
row=N/i;
column=i;
break;
}
}
int sn[N];
for(int i=0; i<N; i++)
{
cin>>sn[i];
}
int pos=0;
sort(sn,sn+N,cmp);
int matrix[row][column];
int time=0;
while(pos<N)
{
for(int n=time; n<column-time&&pos<N; n++)
{
matrix[time][n]=sn[pos++];
}
if(pos==N)
break;
for(int n=time+1; n<row-time&&pos<N; n++)
{
matrix[n][column-1-time]=sn[pos++];
}
if(pos==N)
break;
for(int n=column-time-2; n>=time&&pos<N; n--)
{
matrix[row-1-time][n]=sn[pos++];
}
if(pos==N)
break;
for(int n=row-1-time-1; n>time&&pos<N; n--)
{
matrix[n][time]=sn[pos++];
}
if(pos==N)
break;
time++;
}
for(int m=0; m<row; m++)
{
for(int n=0; n<column; n++)
{
if(n==0)
{
cout<<matrix[m][n];
}
else
cout<<' '<<matrix[m][n];
}
cout<<endl;
}
}