原题:https://pintia.cn/problem-sets/994805342720868352/problems/994805363117768704
这一题是需要根据序列构造spiral matrix。
- 关于螺旋的方式我构造了两个增量数组:
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
这样就很容易根据前一个位置得到下一个位置了,还要注意判断边界。
- 我把需要填充的地方赋值为0,不需要填充的地方赋值为-1,感觉这样做也是很方便。
- 下面是我的代码
#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;
}
}
}