在n*n方阵里填入1,2,3,…,n*n,要求填成蛇形。例如n=4时方阵为:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
解题思路:
我们可以了解到数字的大概规律就是先从上到下,到左,到上,到右这个顺序填写,我们只要注意临界点即可。
// // main.cpp // c++prime // // Created by SJCHEN on 2019/1/19. // Copyright © 2019 SJCHEN. All rights reserved. // #include <iostream> #include <cstdio> using namespace std; #define MAXN 10 int a[MAXN][MAXN]; int main() { int n,x,y,tot = 0; cin >> n; memset(a, 0, sizeof(a)); tot = a[x = 0][y = n-1] = 1; while (tot < n*n) { while (x+1 < n && !a[x+1][y]) a[++x][y] = ++tot;//下 while (y-1 >= 0 && !a[x][y-1]) a[x][--y] = ++tot;//左 while (x-1 >= 0 && !a[x-1][y]) a[--x][y] = ++tot;//上 while (y+1 < n && !a[x][y+1]) a[x][++y] = ++tot;//右 } for (x = 0; x < n; x++) { for (y = 0; y < n; y++) printf("%3d",a[x][y]); cout << endl; } return 0; }
原文:https://www.cnblogs.com/SJCHEN/p/10542708.html