螺旋矩阵的生成。
感觉麻烦在矩阵的计算上面,开始没转过弯来。
还是审题。按递减顺序。。我以为是从中间开始从小往大转。一下子懵逼了。从大往小,从外往内去计算。
像13这样就只能13行 每行一个。
#include <iostream>
#include <vector>
#include <algorithm>
#define MAX 200
using namespace std;
int num;
int m, n;
vector <int> list;
int map[MAX][MAX];
bool cmp(int n1, int n2) {
return n1 > n2;
}
int main() {
cin >> num;
//计算矩阵大小
m = num, n = 1;
int tn = 2, tm = num / tn;
while (tm >= tn) {
while (num % tn != 0 && tm > tn) {
tn++;
tm = num / tn;
}
if (tm >= tn && tm * tn == num) {
m = tm;
n = tn;
}
tn++;
tm = num / tn;
}
//输入
int temp;
for (int i = 0; i < num; i++) {
cin >> temp;
list.push_back(temp);
}
sort(list.begin(), list.end(), cmp);
//装入矩阵
int minh = 0, maxh = n - 1, minv = 0, maxv = m - 1;//边界
int p = 0;
int h = minh, v = minv;
while (p < num) {
//向右
for (h = minh, v = minv; h <= maxh; h++) {
map[v][h] = list[p++];
}
minv++;
//向下
for (v=minv,h = maxh; v <= maxv; v++) {
map[v][h] = list[p++];
}
maxh--;
if (p >= num)
break;
//向左
for (h=maxh,v = maxv; h >= minh; h-- ) {
map[v][h] = list[p++];
}
maxv--;
//向上
for (v= maxv,h = minh; v >= minv; v--) {
map[v][h] = list[p++];
}
minh++;
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n -1; j++) {
cout << map[i][j] << " ";
}
cout << map[i][n - 1] << endl;
}
return 0;
}