PAT Level B-Spiral Matrix

Title description
This question requires the given N positive integers to be filled in the "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 conditions:

  • m × n is equal to N;
  • m ≥ n;
  • And m − n takes the smallest value among all possible values.

Input format
A positive integer N is given in the
first line, and N positive integers to be filled are given in the second line. All numbers do not exceed 10 4 ​​, and adjacent numbers are separated by spaces.

Output format
Output spiral matrix. Each line contains n numbers, a total of m lines. Adjacent numbers are separated by 1 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

Sample output
98 95 93
42 37 81
53 20 76
58 60 76


Problem solution
Offset array:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int s[10010];
int N, n, m;

int dx[4] = {
    
    0, 1, 0, -1};
int dy[4] = {
    
    1, 0, -1, 0};

int main()
{
    
    
	cin >> N;
	for (int i = 0; i < N; i ++) cin >> s[i];
	
	sort(s, s + N, greater<int>());
	
	for (int i = 1; i <= N / i; i ++)
	    if(N % i == 0)
	    {
    
    
	        m = i;
	        n = N / i;
	    }
	    
	int x = 0, y = 0, dir = 0;
	vector<vector<int>> g(n, vector<int>(m));
	
	for (int i = 0; i < N; i ++)
	{
    
    
		g[x][y] = s[i];
		int a = x + dx[dir], b = y + dy[dir];
		if(a < 0 || a >= n || b < 0 || b >= m || g[a][b])
		{
    
    
			dir = (dir + 1) % 4;
			a = x + dx[dir], b = y + dy[dir];
		}
		x = a, y = b;
	}
	
	for (int i = 0; i < n; i ++)
	{
    
    
	    cout << g[i][0];
		for (int j = 1; j < m; j ++) cout << ' ' << g[i][j];
		cout << endl;
	}
	
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_46239370/article/details/115049283