1105 Spiral Matrix (25point(s))
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
題目大意:
設計思路:
- 總體設計方向是一層一層填充 m x n 的矩陣
- 確定 m 和 n 的值,n 從 sqrt(N) 趨於 0,第一個 N % n == 0 成立即找到
- 確定矩陣有幾層,level = n / 2 + n % 2
- 每一層有四個方向
- 注意:如何保存矩陣?一種方法是直接利用一維數組模擬二維,但操作相對繁瑣,本文采用變長數組進行保存,較爲方便。不要預設矩陣爲 10000 x 10000 大小後進行操作,提交後最後一個測試點會返回各種不同的結果,個人推測是因爲計算過程中要對二維數組進行大量的尋址,造成大量時間空間的浪費,如下極端情況:N 爲 9973 素數時矩陣形狀
9973 0 ……
. 0 0 0 ……
. 0 0 0 ……
. 0 0 0 ……
3 0 0 0 ……
2 0 0 0 ……
1 0 0 0 ……
所有 0 的位置均無實際數據,但因二維數組在內存中是“一維”的,每次存取均要經過很多“0”才能到達正確地址
編譯器:C (gcc)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int comp(const void *a, const void *b)
{
return *(int*)b - *(int*)a;
}
int main()
{
int N, m, n, num[10000];
int i, j, k,level;
scanf("%d", &N);
for(i = 0; i < N; i++)
scanf("%d", num + i);
qsort(num, N, sizeof(int), comp);
for(n = sqrt((double)N); !(n > 0 && N % n == 0); n--)
continue;
m = N / n;
int matrix[m][n];
level = n / 2 + n % 2;
for(i = 0, k = 0; i < level; i++){
for(j = i; k <= N - 1 && j <= n - i - 1; j++)
matrix[i][j] = num[k++];
for(j = i + 1; k <= N - 1 && j <= m - i - 2; j++)
matrix[j][n - i - 1] = num[k++];
for(j = n - i - 1; k <= N - 1 && j >= i; j--)
matrix[m - i -1][j] = num[k++];
for(j = m - 2 - i; k <= N - 1 && j >= i + 1; j--)
matrix[j][i] = num[k++];
}
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
printf("%d%c", matrix[i][j], j != n -1 ? ' ' : '\n');
return 0;
}