1050. Spiral Matrix (25) PAT Class B True Theme

1050. Spiral Matrix (25)

This question requires that the given N positive integers be filled in a "spiral matrix" in a non-increasing order.The so-called "spiral matrix" refers to filling in a clockwise spiral direction starting from the first grid in the upper left corner.The size of the matrix is required to be m rows and N columns, satisfying the following conditions: m*n equals N; m>=n; and m-n takes the minimum of all possible values.

Input format:

The input gives a positive integer N in line 1 and N in line 2 to be filled.All numbers do not exceed 104, and adjacent numbers are separated by spaces.

Output format:

Output spiral matrix.n numbers per line, m rows in total.Adjacent numbers are separated by a space and no extra space is allowed at the end of the line.

Input sample:
12
37 76 20 98 76 42 53 95 60 81 58 93
Output sample:
98 95 93
42 37 81
53 20 76
58 60 76
This question is sorted first by a simple order, followed by a matrix according to the meaning of the title.I don't have any good suggestions here, just slowly debug. I really debugged many times based on the output the first time I did it.At that time, the computer still had some problems 1000*1000 matrix can not be defined, only use 10*10 first, and finally debug it before changing the data in hand, a bitter tear.This is my code:
#include<stdio.h>
#include<math.h>


int main(void)
{
    int N,m,n;
    static int a[10000];
    static int b[10000][10000];
    int i,j,max,s=0;
    scanf("%d",&N);
    n=sqrt(N);
    while(N%n!=0)
    {
        n--;
    }
    if (N/n>n) m=N/n;
    else
    {
        n=N/n;m=N/n;
    }
    for (i=0;i<N;i++)
    {
        scanf("%d",&a[i]);
    }
    for (i=0;i<N;i++)                                           //Sort from large to small
    {
        max=i;
        for (j=i+1;j<N;j++)
        {
            if (a[j]>a[max]) max=j;
        }
        j=a[i];a[i]=a[max];a[max]=j;
    }
    i=0;j=0;
    do
    {
        do
        {
            b[i][j]=a[s];
            s++;j++;
        }while(j<n && b[i][j]==0);
        j--;s--;
        do
        {
            b[i][j]=a[s];
            s++;i++;
        }while(i<m && b[i][j]==0);
        i--;s--;
        do
        {
            b[i][j]=a[s];
            s++;
        }while(b[i][--j]==0 && j>=0);
        j++;s--;
        do
        {
            b[i][j]=a[s];
            s++;
        }while(b[--i][j]==0 && i>=0);
        i++;s--;
    }while(s<N-1);
    for (i=0;i<m;i++)
    {
        for (j=0;j<n;j++)
        {
            if (j!=0) printf(" ");
            printf("%d",b[i][j]);
        }
        printf("\n");
    }
    return 0;
}

Posted on Mon, 06 Jul 2020 11:14:36 -0400 by genius