鏈接:https://pintia.cn/problem-sets/994805342720868352/problems/994805363117768704
題意:給你N個數,將其放入非遞增的螺旋矩陣中,矩陣大小爲m*n,要求:
1)N = m * n
2) m >= n
3) m-n最小
思路:按照走路+轉向的思路,當碰壁(超出矩陣範圍或已有值)就順時針轉向。
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 1e4+10;
int mp[1100][1100];
int n,a[N],r,c;
int nex[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int main(void){
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
r=sqrt(n);
while(n%r) r++;
c=n/r;
if(r<c) swap(r,c);
sort(a+1,a+1+n);
int x=1,y=1,d=0;
for(int i=n;i>=1;i--){
mp[x][y]=a[i];
int tx=x+nex[d][0],ty=y+nex[d][1];
if((tx<1||tx>r||ty<1||ty>c)||mp[tx][ty])
d=(d+1)%4;
x+=nex[d][0];
y+=nex[d][1];
}
for(int i=1;i<=r;i++)
for(int j=1;j<=c;j++)
printf("%d%c",mp[i][j],j==c?'\n':' ');
return 0;
}