题目来源:PAT (Advanced Level) Practice
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 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
words:
Spiral 螺旋 Matrix 矩阵 clockwise 顺时针方向 row 行,排 column 列
题意:
给定N个数,将这N个数从大到小按照顺时针螺旋状排成m行n列的矩阵,其中m>=n且m和n尽可能相等;
思路:
1. 首先将N个数存放当数组a[]中并降序排序;
2. 根据N计算出矩阵的行数m和列数n;
3. 申请一个m行n列的二维数组(建议使用vector来实现),然后从左上角upper-left的位置开始按照顺时针螺旋状从0开始编号(相等于把a[]中的元素依次填充进去,但编号便于程序调试);
4. 每一次填充矩阵的一圈(即上下左右四个边),使用k来控制每次要填充的层,k=0表示最外层,在填充时每填充完一条边便要判断是否已填充了N个数,若是则退出填充,否则继续填充;
5. 输出填充好的矩阵即可;
6. 测试案例中存在较大的素数N,即m很大而n=1,若使用预先分配大小的二维数组则会发生段错误,所以建议使用vector;
//PAT ad 1105 Spiral Matrix
#include <iostream>
using namespace std;
#include <algorithm>
#include <cmath>
#include <vector>
bool cmp(int x,int y)
{
return x>y;
}
int N; //元素个数
int num=0;
int m,n; //行数、列数
void fillMatrix(vector<vector<int> > &matrix,int k) //填充矩阵的第k层
{
int i=k,j=k; //第k层的起始位置
for(;j<n-k;j++)
matrix[i][j]=num++; //上边
if(num==N) return ;
j--;i++;
for(;i<m-k;i++)
matrix[i][j]=num++; //右边
if(num==N) return ;
i--;j--;
for(;j>=k;j--)
matrix[i][j]=num++; //下边
if(num==N) return ;
j++;i--;
for(;i>k;i--)
matrix[i][j]=num++; //左边
if(num==N) return ;
}
int main()
{
int i,j,k=0;
cin>>N;
int a[N];
for(i=0;i<N;i++) //输入
cin>>a[i];
sort(a,a+N,cmp); //降序排序
for(m=sqrt(N);N%m!=0;m++);
n=N/m; //行数
if(m<n) swap(m,n);
vector<vector<int> > matrix(m,vector<int>(n));
while(num<N) //填充,k表示矩阵的层数,从最外边数,为第0层
{
fillMatrix(matrix,k); //填充矩阵的第k层
k++;
}
for(i=0;i<m;i++) //输出
{
for(j=0;j<n-1;j++)
cout<<a[matrix[i][j]]<<" ";
cout<<a[matrix[i][j]]<<endl;
}
return 0;
}