遍历
int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0}; 顺时针
int dx[] = {0, 1, 0, -1}, dy[] = {-1, 0, 1, 0}; 逆时针
c++
#include <bits/stdc++.h>
using namespace std;
const int N = 10010;
int st[2005][2005];
int n;
int a[N];
int main(){
cin >> n;
for (int i = 0; i < n; i ++ ) cin >> a[i];
sort(a, a + n, [](int x, int y){
return x > y;
});
int v = 1e7, r = 0, l = 0;
for (int i = 1; i <= n / i; i ++ ) {
if (n % i == 0) {
int t = n / i, k = i;
if (abs(t - k) < v) {
v = abs(t - k), r = t, l = k;
}
}
}
int res[2005][2005] = {0};
//vector<vector<int>> res(r, vector<int>(l, 0));
int i = 0, j = 0, k = 0, id = 0;
int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
while (id < r * l) {
if (i < 0 || j < 0 || i >= r || j >= l || st[i][j]) {
i -= dx[k];
j -= dy[k];
k = (k + 1) % 4;
}else {
res[i][j] = a[id];
st[i][j] = 1;
id ++;
}
i += dx[k], j += dy[k];
}
for (int i = 0; i < r; i ++ ){
for (int j = 0; j < l; j ++ ) {
cout << res[i][j] << " ";
}
cout << endl;
}
}