P5731 【深基5.习6】蛇形方阵 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
这道题就是纯纯找规律的模拟题,但是在比赛或者思维比较松散的情况下紧张的时候会想不出模拟思路
这时候如果测试数据的范围比较小,如本题的数据最大就到九阶方阵,所以可以手算出每一种类型打表输出,不用去考虑一般规律
当然数据范围比较大的时候还是得怪怪找规律-_-&
这里贴上我的找出规律的代码以及题解中的打表代码
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 int Num[10][10]; 5 int n; 6 int NotBeyound(int H, int L)//判断是否出界,否返回1 7 { 8 if ((H >= 1 && H <= n) && (L >= 1) && (L <= n)) 9 return 1; 10 else 11 return 0; 12 } 13 int main() 14 { 15 scanf("%d", &n); 16 int H = 1, L = 1; 17 int Flag = 2;//状态标记,1左2右3上4下,初始向右 18 Num[1][1] = 1; 19 int N = 2; 20 while (N <= n*n) 21 { 22 if (Flag == 2)//初始向右 23 { 24 if (Num[H][L + 1] == 0 && NotBeyound(H, L+1)) 25 Num[H][++L] = N++; 26 else 27 Flag = 4; 28 } 29 if (Flag == 4) 30 { 31 if (Num[H + 1][L] == 0 && NotBeyound(H + 1, L)) 32 Num[++H][L] = N++; 33 else 34 Flag = 1; 35 } 36 if (Flag == 1) 37 { 38 if (Num[H][L - 1] == 0 && NotBeyound(H, L - 1)) 39 Num[H][--L] = N++; 40 else 41 Flag = 3; 42 } 43 if (Flag == 3) 44 { 45 if (Num[H - 1][L] == 0 && NotBeyound(H - 1, L)) 46 Num[--H][L] = N++; 47 else 48 Flag = 2; 49 } 50 } 51 for (int i = 1; i <= n; i++) 52 { 53 for (int j = 1; j <= n; j++) 54 { 55 printf("%3d", Num[i][j]); 56 } 57 printf("\n"); 58 } 59 return 0; 60 }
打表代码如下
#include <bits/stdc++.h> using namespace std; int n; int main () { cin >> n; if(n == 1) cout << " 1\n"; if(n == 2) cout <<" 1 2\n 4 3\n"; if(n == 3) { cout << " 1 2 3\n"; cout << " 8 9 4\n"; cout << " 7 6 5\n"; } if(n == 4) { cout << " 1 2 3 4\n"; cout << " 12 13 14 5\n"; cout << " 11 15 16 6\n"; cout << " 10 9 8 7\n"; } if(n == 5) { cout << " 1 2 3 4 5\n"; cout << " 16 17 18 19 6\n"; cout << " 15 24 25 20 7\n"; cout << " 14 23 22 21 8\n"; cout << " 13 12 11 10 9\n"; } if(n == 6) { cout << " 1 2 3 4 5 6\n"; cout << " 20 21 22 23 24 7\n"; cout << " 19 32 33 34 25 8\n" ; cout << " 18 31 36 35 26 9\n"; cout << " 17 30 29 28 27 10\n"; cout << " 16 15 14 13 12 11\n"; } if(n == 7) { cout << " 1 2 3 4 5 6 7\n"; cout << " 24 25 26 27 28 29 8\n"; cout << " 23 40 41 42 43 30 9\n"; cout << " 22 39 48 49 44 31 10\n"; cout << " 21 38 47 46 45 32 11\n"; cout << " 20 37 36 35 34 33 12\n"; cout << " 19 18 17 16 15 14 13\n"; } if(n == 8) { cout << " 1 2 3 4 5 6 7 8\n"; cout << " 28 29 30 31 32 33 34 9\n"; cout << " 27 48 49 50 51 52 35 10\n"; cout << " 26 47 60 61 62 53 36 11\n"; cout << " 25 46 59 64 63 54 37 12\n"; cout << " 24 45 58 57 56 55 38 13\n"; cout << " 23 44 43 42 41 40 39 14\n"; cout << " 22 21 20 19 18 17 16 15\n"; } if(n == 9) { cout << " 1 2 3 4 5 6 7 8 9\n"; cout << " 32 33 34 35 36 37 38 39 10\n"; cout << " 31 56 57 58 59 60 61 40 11\n"; cout << " 30 55 72 73 74 75 62 41 12\n"; cout << " 29 54 71 80 81 76 63 42 13\n"; cout << " 28 53 70 79 78 77 64 43 14\n"; cout << " 27 52 69 68 67 66 65 44 15\n"; cout << " 26 51 50 49 48 47 46 45 16\n"; cout << " 25 24 23 22 21 20 19 18 17\n"; } return 0; }
标签:洛谷,P5731,int,打表,include,规律 From: https://www.cnblogs.com/WKWKSL/p/17283785.html