1105. 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
- 题目具体分析
题目本身不是很难,意思特别容易理解,难点在于怎么进行clockwise spiral.应该是翻译为顺时针螺旋排列把,其实又不是排序,而是排列。不过这个排列是在排序的基础上进行的。 - 1
对输入的N个数字,找出合适的输出数组大小。输出数组是这样的,行列的乘积==N,行数大于等于列数。一定要看清是行数大于或者等于列数。我就是记成了行数不能等于列数,(哭哭)。对于求对应的行数和列数,只要简单的两重循环求进行了,不会超时的。 - 2
数组排序。=,C++数组排序调用系统的sort函数即可,Java更简单,Arrays.sort。不过,150ms,Java肯定超时。这里有一个小技巧,碰到小于400ms的直接选择C或者C++,Java一般不用想了,而且特殊情况。当然很少了。
3
clockwise spiral 顺时针螺旋排列,这个是本题最麻烦的,我一次写也不会,是参考了,别人写的。其实,就是从左往右,从上往下,从右往左,从下往上四大块内容,知道这个就so easy啦~ 这里,也要注意一下,在while(true)里面结束的条件,是index==-1啦。 - 具体代码如下啦
#include <iostream>
#include <algorithm>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char *argv[]) {
int N;
cin>>N;
int num[N];
int m = 2;
int n = 1;
int min = N;
int row=0,col=0;
for(int k=0;k<N;k++){
cin>>num[k];
}
if(N==1){
cout<<num[0]<<endl;
}
else{
for(n=1;n<=N;n++){
for(m=n;m<=N;m++){
if(m*n==N){
if(m-n<min){
min = m-n;
row = m;
col = n;
}
}
}
}
sort(num,num+N);
int result[row][col];
for(int k=0;k<row;k++){
for(int p=0;p<col;p++){
result[k][p] = -1;
}
}
int index = N-1;
//cout<<row<<" "<<col<<endl;
int row1 = 0,row2 = row-1,col1= 0,col2 = col-1;
while(true){
// 从左往右
for(int i=col1;i<=col2;i++){
result[row1][i] = num[index--];
//cout<<"["<<row1<<","<<i<<"]"<<endl;
}
if(index==-1)
break;
// cout<<index<<endl;
// 从上往下
row1++;
for(int i=row1;i<=row2;i++){
result[i][col2] = num[index--];
//cout<<"["<<i<<","<<col2<<"]"<<endl;
}
if(index==-1)
break;
// 从右往左
col2--;
for(int i=col2;i>=col1;i--){
result[row2][i] = num[index--];
//cout<<"["<<row2<<","<<i<<"]"<<endl;
}
if(index==-1)
break;
//
// 从下往上
row2--;
for(int i=row2;i>=row1;i--){
result[i][col1] = num[index--];
//cout<<"["<<i<<","<<col1<<"]"<<endl;
}
col1++;
if(index==-1)
break;
}
for(int i=0;i<row;i++){
cout<<result[i][0];
for(int j=1;j<col;j++){
cout<<" "<<result[i][j];
}
cout<<endl;
}
}
return 0;
}