一、思路
1.将输入从大到小排序
2.根据数据总个数,计算答案数组的两维(m[行数],n[列数])
3.分别定义上下左右4个边界,并实时维护
top < bottom && left < right
4.按照答案数组的第top行 -> 第right列[由上至下] -> 第bottom行倒序 -> 第left列[由下至上]
的顺序向答案数组中填数
5.每次填完一行/一列,其对应的边界变化
1 [+1 / -1]
6.当4个边界变化不合法时,循环结束
7.输出答案
二、C++代码
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int N = 10010;
int len;
int w[N];
int main(){
cin >> len;
for(int i = 0; i < len; i++) cin >> w[i];
sort(w, w + len, greater<int>());
int m,n;//记录输入得到的二维数组的行数,列数
for(int i = 1; i <= len / i; i++)
if(len % i == 0)
m = len / i, n = i;
int cnt = 0;
vector<vector<int>> res(m, vector<int>(n, 0));
int top = 0, bottom = m - 1, left = 0, right = n - 1;
while(1){
for(int i = left; i <= right; i++) res[top][i] = w[cnt++];
top++;
if(top > bottom) break;
for(int i = top; i <= bottom; i++) res[i][right] = w[cnt++];
right--;
if(right < left) break;
for(int i = right; i >= left; i--) res[bottom][i] = w[cnt++];
bottom--;
if(bottom < top) break;
for(int i = bottom; i >= top; i--) res[i][left] = w[cnt++];
left++;
if(left > right) break;
}
for(int i = 0; i < m; i++){
cout << res[i][0];
for(int j = 1; j < n; j++) cout << ' ' << res[i][j];
cout << endl;
}
return 0;
}