矩阵 螺旋填充可以提前规定好上下左右四个方向,然后根据所在的位置是否越界或者是否已经被 填充过相应地改变方向。比如 dx=[1,0,-1,0], dy=[0,1,0,-1],设置初试方向 dir=0,每次移动的 时候只要当前位置加上对应的 dx 和 dy,要改变方向的时候就 dir=(dir+1)%4 就可以了,是否 填充满可以直接用填充数量判断。
1105 Spiral Matrix (25 分)
This time your job is to fill a sequence of N positive integers into a spiral matrix in non-increasing order. A spiral matrix is filled in from the first element at the upper-left corner, then move in a clockwise spiral. The matrix has m rows and n columns, where m and n satisfy the following: m×n must be equal to N; m≥n; and m−n is the minimum of all the possible values.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N. Then the next line contains N positive integers to be filled into the spiral matrix. All the numbers are no more than 104. The numbers in a line are separated by spaces.
Output Specification:
For each test case, output the resulting matrix in m lines, each contains n numbers. There must be exactly 1 space between two adjacent numbers, and no extra space at the end of each line.
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
AC代码:
#include<cstdio>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#pragma warning(disable:4996)
using namespace std;
#include<string>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<queue>
const int maxn = 100 + 10;
const int INF = 0x7fffffff;
bool cmp(int &x, int &y) {
return x > y;
}
int main(){
int n;
scanf("%d", &n);
int row = n, col = 1;
vector<int> ve(n);
for (int i = 0; i < n; i++)
scanf("%d", &ve[i]);
sort(ve.begin(), ve.end(), cmp);
int min_sub = INF;
for (int i = 1; i <= sqrt(n); i++) {
if (n%i == 0) {
if (abs(i - n / i) < min_sub) {
row = i;
col = n / row;
}
}
}
if (col > row)swap(col, row);
//printf("%d %d", row, col);
//for (int i = 0; i < n; i++)
// printf("%d ", ve[i]);
//printf("\n");
int ans[maxn][maxn] = { 0 }, book[maxn][maxn] = { 0 };
int cnt = 0, dir = 0;
int x = 0, y = 0;
int dx[4] = { 1,0,-1,0 }, dy[4] = { 0,1,0,-1 };
while (cnt < n) {
ans[y][x] = ve[cnt];
book[y][x] = 1;
//printf("x:%d y:%d\n", x, y);
//for (int i = 0; i < row; i++)
// for (int j = 0; j < col; j++)
// printf("%d%c", ans[i][j], j == col - 1 ? '\n' : ' ');
//printf("\n\n");
if (x + dx[dir] < 0 || x + dx[dir] == col ||
y + dy[dir] < 0 || y + dy[dir] == row ||
book[y + dy[dir]][x + dx[dir]] == 1)
dir = (dir + 1) % 4;
x = x + dx[dir];
y = y + dy[dir];
cnt++;
}
for (int i = 0; i < row; i++)
for(int j = 0;j < col; j++)
printf("%d%c", ans[i][j], j == col - 1 ? '\n' : ' ');
return 0;
}