A1105. Spiral Matrix

This time your job is to fill a sequence of N positive integers into a spiral matrix in non-increasing order. A spiral matrixis filled in from the first element at the upper-left corner, then move in a clockwise spiral. The matrix has m rows and ncolumns, 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

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<algorithm>
 4 #include<math.h>
 5 using namespace std;
 6 int G[10000][10000];
 7 int N, num[1000000], index = 0;
 8 bool cmp(int a, int b){
 9     return a > b;
10 }
11 int main(){
12     scanf("%d", &N);
13     for(int i = 0; i < N; i++)
14         scanf("%d", &num[i]);
15     int sqr = sqrt(N * 1.0);
16     int m, n;
17     for(n = sqr; N % n != 0; n--);
18     m = N / n;
19     sort(num, num + N, cmp);
20     int k = 0, j = 0, times = 0;
21     while(index < N){
22         if(N - index == 1){
23             G[k][j] = num[index];
24             break;
25         }
26         while(j < n - 1 - times && index < N){
27             G[k][j++] = num[index++];
28         }
29         while(k < m - 1 - times && index < N){
30             G[k++][j] = num[index++];
31         }
32         while(j > times && index < N){
33             G[k][j--] = num[index++];
34         }
35         while(k > times && index < N){
36             G[k--][j] = num[index++];
37         }
38         k++;
39         j++;
40         times++;
41     }
42     for(int i = 0; i < m; i++){
43         for(int j = 0; j < n; j++){
44             if(j == n - 1) 
45                 printf("%d", G[i][j]);
46             else 
47                 printf("%d ", G[i][j]);
48         }
49         printf("
");
50     }
51     cin >> N;
52     return 0;
53 }
View Code

总结:

1、采用旋转填充二维数组的方式的时候要注意,当遇到图形中心是一个时会出现死循环,需要特殊处理一下。如图:

                                                                                     

2、测试数据:测试只有1个元素、只有1列元素、边长为奇数的正方形、边长偶数的正方形。

3、超时有可能是因为出现了死循环,而不一定是复杂度不对。

4、方法,设顶点为(x,y),边长为m、n。填充一圈后变为顶点(x+1, y+1),边长变为m - 2, n - 2。

原文地址:https://www.cnblogs.com/zhuqiwei-blog/p/8564390.html