Pat B 1050 spiral matrix

Keywords: MySQL

Title Description:

This question requires that the given n positive integers be filled in "spiral matrix" in non increasing order. The so-called "spiral matrix" refers to the first lattice in the upper left corner, which is filled in a clockwise spiral direction. It is required that the scale of matrix is m rows and N columns, which satisfies the following conditions: m × n is equal to N; m ≥ n; and m − n takes the minimum of all possible values.
Input format:
Input gives a positive integer N in line 1, and N positive integers to be filled in line 2. All numbers are no more than 10
4, adjacent numbers are separated by spaces.
Output format:
Output spiral matrix. n numbers per line, m lines in total. Adjacent numbers are separated by 1 space, and there must be no extra space at the end of the line.

Input example:
12
37 76 20 98 76 42 53 95 60 81 58 93
Output example:
98 95 93
42 37 81
53 20 76
58 60 76

My AC Code:

// Pat? 1050? Helices

# include <stdio.h>
# include <math.h>
# include <stdlib.h>
# include <algorithm>
# define Max_Size 10010
# define Min_Size 100
using namespace std;

int Get_n(float N)
{
	int i;

	for (i=(int)sqrt(N);i>0; i--)
	{
		if ((int)N%i == 0)
			return i;
	}
}
int main(void)
{
	int N;
	int i, j, k;

	int m, n;
	scanf("%d",&N);
	n = Get_n(N);
	m = N/n;

	int A[N+10];
	int B[m+1][n+1];

	// Initialization
	for (i=0; i<m; i++)
	{
		for (j=0; j<n; j++)
		{
			B[i][j] = 0;
		}
	}

	for (i=0; i<N; i++)
	{
		scanf("%d",&A[i]);
	}
	sort(A,A+N); // sort

	// Start to put it in row m and column n
	i=0; j=0; k=N-1;
	B[i][j] = A[k--];
	while (k>=0)
	{
		// Turn right
		while (!B[i][j+1] && j+1<n )
		{
			B[i][++j] = A[k--];
		}
		// Go down
		while (!B[i+1][j] && i+1<m )
		{
			B[++i][j] = A[k--];
		}
		// Turn left
		while (!B[i][j-1] && j-1>=0)
		{
			B[i][--j] = A[k--];
		}
		// Turn left
		while (!B[i-1][j] && i-1>=0)
		{
			B[--i][j] = A[k--];
		}
	}

	for (i=0; i<m; i++)
	{
		for (j=0; j<n; j++)
		{
			printf("%d",B[i][j]);
				if (j<n-1)
					printf(" ");
		}
		printf("\n");
	}
	return 0;
}

RRR  

Posted by BLaZuRE on Sun, 20 Oct 2019 13:34:47 -0700