螺旋矩阵填充算法
给定 N 个正整数,需要将它们按非递增顺序填入一个螺旋矩阵中。矩阵填充从左上角第一个元素开始,按顺时针螺旋方向前进。矩阵有 m 行 n 列,需满足 m × n = N,m ≥ n,且 m - n 在所有可能组合中最小。
输入格式:
每个输入文件包含一个测试用例。第一行给出正整数 N。接下来一行包含 N 个待填入螺旋矩阵的正整数(均不超过 10⁴),数字间以空格分隔。
输出格式:
输出 m 行矩阵,每行包含 n 个数字。相邻数字间恰好有一个空格,行末无多余空格。
样例输入:
12 37 76 20 98 76 42 53 95 60 81 58 93
样例输出:
98 95 93 42 37 81 53 20 76 58 60 76
参考代码:
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAX = 10005;
int numbers[MAX];
bool used[105][105] = {false};
int result[105][105];
bool descending(int a, int b) {
return a > b;
}
int main() {
int total;
scanf("%d", &total);
for (int i = 0; i < total; i++) {
scanf("%d", &numbers[i]);
}
sort(numbers, numbers + total, descending);
int minDiff = total;
int rows = total, cols = 1;
for (int r = 1; r <= total; r++) {
if (total % r == 0) {
int c = total / r;
if (r >= c && (r - c) < minDiff) {
rows = r;
cols = c;
minDiff = r - c;
}
}
}
int curRow = 0, curCol = 0, idx = 0, direction = 1;
while (true) {
if (!used[curRow][curCol]) {
result[curRow][curCol] = numbers[idx++];
used[curRow][curCol] = true;
}
if (idx == total) break;
bool canRight = (curCol + 1 < cols) && !used[curRow][curCol + 1];
bool canDown = (curRow + 1 < rows) && !used[curRow + 1][curCol];
bool canLeft = (curCol - 1 >= 0) && !used[curRow][curCol - 1];
bool canUp = (curRow - 1 >= 0) && !used[curRow - 1][curCol];
if (direction == 1) {
if (canRight) {
curCol++;
} else if (canDown) {
curRow++;
direction = 2;
} else if (canLeft) {
curCol--;
direction = 3;
} else if (canUp) {
curRow--;
direction = 4;
}
} else if (direction == 2) {
if (canDown) {
curRow++;
} else if (canLeft) {
curCol--;
direction = 3;
} else if (canRight) {
curCol++;
direction = 1;
} else if (canUp) {
curRow--;
direction = 4;
}
} else if (direction == 3) {
if (canLeft) {
curCol--;
} else if (canUp) {
curRow--;
direction = 4;
} else if (canRight) {
curCol++;
direction = 1;
} else if (canDown) {
curRow++;
direction = 2;
}
} else if (direction == 4) {
if (canUp) {
curRow--;
} else if (canRight) {
curCol++;
direction = 1;
} else if (canDown) {
curRow++;
direction = 2;
} else if (canLeft) {
curCol--;
direction = 3;
}
}
}
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
printf("%d", result[r][c]);
if (c != cols - 1) printf(" ");
}
if (r != rows - 1) printf("\n");
}
return 0;
}