A1105 Spiral Matrix

原题:https://pintia.cn/problem-sets/994805342720868352/problems/994805363117768704
这一题是需要根据序列构造spiral matrix。

  1. 关于螺旋的方式我构造了两个增量数组:
	int Y[4] = { 1,0,-1,0 };
	int X[4] = { 0,1,0,-1 };

以及一个方向变量:

int di = 0;	//direction, 0 is right; 1 is down; 2 is left; 3 is up

这样就很容易根据前一个位置得到下一个位置了,还要注意判断边界。

  1. 我把需要填充的地方赋值为0,不需要填充的地方赋值为-1,感觉这样做也是很方便。
  2. 下面是我的代码
#include <iostream>
#include <string>
#include <set>
#include <map>
#include<queue>
#include<stack>
#include<algorithm>
#include<cmath>

//new and delete
//A1105 Spiral Matrix
using namespace std;

void Get_mn(int a,int &m,int &n) {
	int sqr = (int)sqrt(a);
	for (int i = 1; i <= sqr; i++) {
		if (a % i == 0)
			n = i;
	}
	m = a / n;

}
bool cmp(int a, int b) {
	return a > b;
}
const int MaxM = 101;
const int MaxN = 10001;
//螺旋矩阵
int matrix[MaxN][MaxM];
//输入序列
int seq[MaxN] = { 0 };

int m, n;	//m*n螺旋矩阵

bool GetNext(int &x, int &y, int &di) {
	int Y[4] = { 1,0,-1,0 };
	int X[4] = { 0,1,0,-1 };
	if (matrix[x + X[di]][y + Y[di]] == 0 && x + X[di]>=0 && y + Y[di]>=0) {
		x = x + X[di];
		y = y + Y[di];
		return true;
	}
	else {
		di = (di + 1) % 4;
		return false;
	}

}
void fillMat(int N) {
	int di = 0;	//direction, 0 is right; 1 is down; 2 is left; 3 is up
	int x = 0, y = 0;

	for (int i = 0; i < N; i++) {
		matrix[x][y] = seq[i];
		int num = 0;
		while (GetNext(x, y, di) == false) {
				num++;
				if (num > 2)
					break;
		}
	}

}
int main() {
	int N;
	cin >> N;
	fill(matrix[0], matrix[0] + MaxM * MaxN, -1);
	for (int i = 0; i < N; i++) {
		cin>>seq[i];
	}
	sort(seq, seq + N, cmp);
	Get_mn(N, m, n);
	//把需要填空的地方变成0
	for (int i = 0; i < m; i++)
		for (int j = 0; j < n; j++)
			matrix[i][j] = 0;

	fillMat(N);

	//输出
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			cout << matrix[i][j];
			if (j < n - 1)
				cout << " ";
			else
				cout << endl;
		}
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值