# 蛇形方阵 C语言

17 篇文章 0 订阅

4

1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7

# Copy 方式 2 :

#include<stdio.h>
int a[10][10];    //这里定义全局变量,默认数组每个元素初始化为 0
int main(){
int n;
int k = 0; // 蛇形走位的初始值,每次循环成功 ++k;
scanf("%d",&n);
int x = 1,y = 0;

while( k < n*n){

// a[x][y+1] 是目标位置
//从左往右 , 判断如果没有超过边界并且目标位置没有被覆盖过则可以进行赋值
while( y < n  && a[x][y+1] == 0 )
{  a[x][++y] = ++k;}

//从上往下 ,
while( x < n  && a[x+1][y] == 0  )
{ a[++x][y] = ++k;}

//从右往左
while( y > 1 && a[x][y-1] == 0  )
{  a[x][--y] = ++k;}

//从下往上
while( x > 1  && a[x-1][y] == 0  )
{  a[--x][y] = ++k;}

}

for(int i = 1; i<= n; i++){
for(int j = 1; j <= n; j++){
printf("%3d",a[i][j]);
}
printf("\n");
}
return 0;
}


# Copy 方式1:

#include <iostream>
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;
}

10-11 1867

01-06 801
06-04 1万+
10-26 1191
04-05 706
01-05 3150
06-05 4333
05-19 437
07-01 992
02-27 4739
03-15 1221

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。