PAT 1105 Spiral Matrix

Posted mr-stn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT 1105 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 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 ncolumns, where m and n satisfy the following: m×n must be equal to N; mn; 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 Npositive integers to be filled into the spiral matrix. All the numbers are no more than 1. 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

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool cmp(int a, int b){
  return a>b;
}
int main(){
 int N, i, j, n;
 scanf("%d", &N);
 for(i=1; i*i<N+1; i++)  if(N%i==0) n=i;
 vector<vector<int> > arr(N/n, vector<int>(n)), vis(N/n, vector<int>(n, false));
 vector<int> v(N);
 for(i=0; i<N; i++) scanf("%d", &v[i]);
 sort(v.begin(), v.end(), cmp);
 int x=0, y=0, dir=0;
 for(i=0; i<N; i++){
   if(dir==0){
     if(y==n || vis[x][y]){
       dir=1;
       y--;
       x++;
       i--;
     }else{
       arr[x][y] = v[i];
       vis[x][y] = true;
       y++;
     }
   }else if(dir==1){
     if(x==N/n || vis[x][y]){
       x--;
         y--;
       dir=2;
         i--;
     }else{
       arr[x][y] = v[i];
       vis[x][y] = true;
       x++;
     }
   }else if(dir==2){
     if(y==-1 || vis[x][y]){
       y++;
       x--;
       dir=3;
       i--;
     }else{
       arr[x][y] = v[i];
       vis[x][y] = true;
       y--;
     }
   }else{
     if(x==-1 || vis[x][y]){
       dir=0;
       x++;
       y++;
       i--;
     }else{
       arr[x][y] = v[i];
       vis[x][y] = true;
       x--;
     }
   }
 }

 for(i=0; i<N/n; i++){
   cout<<arr[i][0];
   for(j=1; j<n; j++) cout<<" "<<arr[i][j];
   cout<<endl;
 }
 return 0; 
}

 



以上是关于PAT 1105 Spiral Matrix的主要内容,如果未能解决你的问题,请参考以下文章

1105. Spiral Matrix (25)模拟——PAT (Advanced Level) Practise

1105. Spiral Matrix (25)模拟——PAT (Advanced Level) Practise

PAT 1105 Spiral Matrix

PAT 1105 Spiral Matrix

PAT_A1105#Spiral Matrix

PAT 甲级 1105 Spiral Matrix