PAT A1105 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 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
思路:
本题是一道模拟题,就按照题目要求的思路进行模拟即可,将序列降序排序后,螺旋式地填充到一个结果数组中,按照最终位置来存,本题有2个细节点:
1.当输入数据只有一个数据的时候需要单独判断输出
2.当矩阵是个N*N的矩阵的时候,此时矩阵螺旋输出后最里面一圈会出现只有一个数据的情况,如果不单独处理会出现死循环,只要判断是最后一个数据的时候将它单独处理即可。
代码实现
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
int ans[110][110];
int main() {
int num,n,m,sqr,cnt=0;
cin>>num;
vector<int> sq(num+1);
sqr=sqrt(1.0*num);
while(num%sqr!=0) sqr++;
m=max(num/sqr,sqr);
n=min(num/sqr,sqr);
for(int i=0; i<num; i++) scanf("%d",&sq[i]);
if(num==1) {
printf("%d",sq[0]);
return 0;
}
sort(sq.begin(),sq.end(),greater<int> {});
int row=1,col=1,L=1,UP=1,tn=n,tm=m;
while(cnt<num) {
while(cnt<num&&col<n) //向右走
ans[row][col++]=sq[cnt++];
while(cnt<num&&row<m) //向下走
ans[row++][col]=sq[cnt++];
while(cnt<num&&col>L) //向左走
ans[row][col--]=sq[cnt++];
while(cnt<num&&row>UP)//向上走
ans[row--][col]=sq[cnt++];
m--;
n--;//缩小边界
UP++;
L++;//缩小边界
col++;//从第二圈缩小矩阵的第一个元素开始
row++;
if(cnt==num-1)
ans[row][col]=sq[cnt++];
}
for(int i=1; i<=tm; i++) {
for(int j=1; j<=tn; j++) {
printf("%d",ans[i][j]);
if(j<tn) printf(" ");
else printf("\n");
}
}
return 0;
}