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.
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 1. The numbers in a line are separated by spaces.
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.
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
刘汝佳老师的思路,从第一个格子开始走,每次看下一个格子是不是没走过且没越界,
满足条件则走,不满足直接换一个方向。
1 #include <cstdio> 2 #include <cmath> 3 #include <algorithm> 4 using namespace std; 5 6 const int maxn = 1e4 + 5, maxe = 100 + 5; 7 int val[maxn]; 8 int gaze[maxe][maxe]; 9 10 bool cmp(const int a, const int b) { 11 return a > b; 12 } 13 14 int main() { 15 int N; 16 scanf("%d", &N); 17 for(int i = 1; i <= N; i ++) { 18 scanf("%d", &val[i]); 19 } 20 sort(val + 1, val + N + 1, cmp); 21 int b = sqrt(N); 22 while(true) { 23 if(N % b == 0) break; 24 b --; 25 } 26 int n = N / b, m = b; 27 int x = 1, y = 0, cnt = 0; 28 while(cnt < N) { 29 while(y + 1 <= m && !gaze[x][y + 1]) gaze[x][++ y] = val[++ cnt]; 30 while(x + 1 <= n && !gaze[x + 1][y]) gaze[++ x][y] = val[++ cnt]; 31 while(y - 1 > 0 && !gaze[x][y - 1]) gaze[x][-- y] = val[++ cnt]; 32 while(x - 1 > 0 && !gaze[x - 1][y]) gaze[-- x][y] = val[++ cnt]; 33 } 34 for(int i = 1; i <= n; i ++) { 35 for(int j = 1; j <= m; j ++) { 36 if(j != 1) printf(" "); 37 printf("%d", gaze[i][j]); 38 } 39 printf("\n"); 40 } 41 return 0; 42 }
第一次做这个题是C语言老师的课堂作业,当时可能写了有七八十行吧,后来在刘汝佳书上看到了一种
精妙的解法,随后忘记了,还有一次在区域赛真题训练赛的时候也写过,当时也是三个人写了好久,绕进去了。
那天打蓝桥杯校赛的时候也写过一个,直接copy的。今天又来了,写了半天发现那个上次被我改出来的点我又忘记了。
真是吐了呀,回顾了一下刘汝佳老师的代码,发现真的是好想而且思路简单。我为什么没想到了,吐了。
1105 Spiral Matrix (25分)(蛇形填数)
原文:https://www.cnblogs.com/bianjunting/p/13211291.html