PTA甲级考试真题练习105——1105 Spiral Matrix

题目

PTA甲级考试真题练习105——1105 Spiral Matrix_第1张图片

思路

水题,递归存储在二维数组即可

代码

#include 
#include 
#include
using namespace std;
const int nmax = 10;
vector<int> vec;
vector < vector<int>> graph;
int k = 0;
void DFS(int rs, int re, int cs, int ce) {
     
	for (int i = cs; i <= ce; ++i)  graph[rs][i] = vec[k++];
	for (int i = rs + 1; i <= re; ++i)    graph[i][ce] = vec[k++];
	if(rs!=re)
		for (int i = ce - 1; i >= cs; --i) graph[re][i] = vec[k++];
	if(cs!=ce)
		for (int i = re - 1; i > rs; --i) graph[i][cs] = vec[k++];
	if(k!=vec.size())
		DFS(rs + 1, re - 1, cs + 1, ce - 1);
}
int main()
{
     
	int n;
	cin >> n;
	vec.resize(n);
	for (int i = 0; i < n; ++i) cin >> vec[i];
	sort(vec.begin(), vec.end(), greater<int>());
	//计算边界
	int ans = sqrt(n);
	int row, column;
	row = column = ans;
	while (row * column != n) {
     
		if (row * column < n) row++;
		else column--;
	}
	graph.resize(row);
	for (int i = 0; i < row; ++i) graph[i].resize(column);
	DFS(0, row - 1, 0, column - 1);
	for (auto& p : graph) {
     
		cout << p[0];
		for (int i = 1; i < p.size(); ++i)
			cout << " " << p[i];
		cout << endl;
	}
	return 0;
}

你可能感兴趣的:(PAT甲级考试真题练习)