PAT A1105 Spiral Matrix (25point(s))

Scroll Down

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 $10^4$. 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>
#include<cmath>

using namespace std;

int main()
{
	int n;
	cin >> n;
	vector<int> arr(n, 0);
	// 行、列、根号n
	int r = 0, c = 0, sqrtn = (int)sqrt(n);
	for (int i = 1; i <= n; i++)
		cin >> arr[i - 1];
	sort(arr.begin(), arr.end());

	// 寻找使r-c最小的r和c
	for (c = sqrtn; c >= 1; c--) {
		if (n%c == 0) {
			r = n / c;
			break;
		}
	}

	// 结果是一个r行,c列的二维数组
	vector<vector<int>> ans(r, vector<int>(c));

	int i = 0, j = 0, count = n - 1, round = 1;
	// 控制方向
	bool left = false, right = true, down = false, up = false;

	// j的取值范围为[round-1,c-round+1],i的取值范围为[round-1, r-round+1]
	while (count >= 0) {
		if (left) {
			ans[i][j--] = arr[count--];
			// 到达左边界,向上拐
			if (j < round - 1) {
				left = false;
				up = true;
				j++;
				i--;
			}
		}
		else if (right) {
			ans[i][j++] = arr[count--];
			// 到达右边界,向下拐
			if (j >= c - round + 1) {
				right = false;
				down = true;
				i++;
				j--;
			}
		}
		else if (down) {
			ans[i++][j] = arr[count--];
			// 到达下边界,向左拐
			if (i >= r - round + 1) {
				down = false;
				left = true;
				j--;
				i--;
			}
		}
		else {
			ans[i--][j] = arr[count--];
			// 到达上边界,向右拐
			if (i <= round - 1) {
				// 修改起点
				i = round;
				j = round;
				round++;
				up = false;
				right = true;
			}
		}
	}
	for (int i = 0; i < r; i++) {
		for (int j = 0; j < c - 1; j++) cout << ans[i][j] << " ";
		cout << ans[i][c - 1] << endl;
	}
	return 0;
}