A1105 Spiral Matrix (25 point(s))

递归

1. 原文

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 mrows and n columns, where m and n satisfy the following: m×n must be equal to N; mn; and mn 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:

1
2
12
37 76 20 98 76 42 53 95 60 81 58 93

Sample output:

1
2
3
4
98 95 93
42 37 81
53 20 76
58 60 76

2. 解析

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
int num[10010]={};
bool cmp(int x,int y){
return x>y;
}
int getnum(int x){
int a=sqrt(1.0*x);
while(a!=1){
if (x%a==0)
{
break;
}else{
a--;
}
}
return a;
}
int matrix[10010][10010];
int main()
{
int N;
scanf("%d",&N);
for (int i = 0; i < N; ++i)
{
scanf("%d",&num[i]);
}
sort(num,num+N,cmp);
int n=getnum(N);
int m=N/n;
int level=N/2+N%2;
int t=0;
for (int j = 0; j < level; ++j)
{
for (int i = j; i < n-j&&t<N; ++i)
{
matrix[j][i]=num[t++];
}
for (int i = 1+j; i < m-j&&t<N; ++i)
{
matrix[i][n-1-j]=num[t++];
}
for (int i = n-2-j; i >= j&&t<N ; i--)
{
matrix[m-1-j][i]=num[t++];
}
for (int i = m-2-j; i >= j+1&&t<N ; i--)
{
matrix[i][j]=num[t++];
}
}
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (j!=0)
{
printf(" ");
}
printf("%d",matrix[i][j]);
}
printf("\n");
}
return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1105/
  • 发布时间: 2019-09-03 12:30
  • 更新时间: 2021-10-29 14:07
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!