A1105 Spiral Matrix ,模拟
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"bits/stdc++.h"
using namespace std;
int directions[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
int direct = 0;
void change() {
direct ++;
direct %= 4;
}
int *p;
int m,n;
int getV(int x,int y) {
return p[y*n+x];
}
void setV(int x,int y,int v) {
p[y*n+x] = v;
}
bool ok(int x,int y) {
if(x >= n || y >= m)
return false;
if(x < 0 || y < 0)
return false;
return getV(x,y) == -1;
}
void step(int &x,int &y,int v) {
setV(x,y,v);
if(!ok(x+directions[direct][0],y+directions[direct][1])) {
change();
}
x += directions[direct][0];
y += directions[direct][1];
}
int main() {
// freopen("input.txt","r",stdin);
int num;
cin >> num;
vector<int> a(num);
for(int i=0; i<num; i++) scanf("%d",&a[i]);
m = num; n = 1;
while(true){
if(m <= 0 || m < num/m)
break;
if(num % m == 0)
n = num/m;
m --;
}
m = num / n;
int ans[m][n];
p = ans[0];
fill(p,p+m*n,-1);
sort(a.rbegin(),a.rend());
int x = 0;
int y = 0;
for(int i=0; i<num; i++) {
step(x,y,a[i]);
}
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
if(j != n-1)
printf("%d ",ans[i][j]);
else
printf("%d\n",ans[i][j]);
}
}
}