PAT----A1105 Spiral Matrix (25 分)

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]);
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值