CODE[VS]1160 蛇形矩阵

题目描述 Description

小明玩一个数字游戏,取个n行n列数字矩阵(其中n为不超过100的奇数),数字的填补方法为:在矩阵中心从1开始以逆时针方向绕行,逐圈扩大,直到n行n列填满数字,请输出该n行n列正方形矩阵以及其的对角线数字之和.

 

输入描述 Input Description

n(即n行n列)

 

输出描述 Output Description

n+1行,n行为组成的矩阵,最后一行为对角线数字之和

 

样例输入 Sample Input

3

样例输出 Sample Output

5 4 3
6 1 2
7 8 9
25

 

好题,好题。

 

模拟。

 

 1 /*
 2 作者:我颈椎不好
 3 题目:p1160 蛇形矩阵
 4 */
 5 
 6 #include<iostream>
 7 #include<cstdio>
 8 #include<cmath>
 9 #include<algorithm>
10 #include<cstring>
11 using namespace std;
12 
13 int n,now=1,s,fx=1,tot=1,ans;
14 int a[102][102];
15 
16 int main()
17 {
18     scanf("%d",&n);
19     s=n/2+1;
20     int i=s,j=s;
21     a[i][j]=now;
22     now++;
23     while(tot!=n*n)
24     {
25         if(fx==1&&j-i==1) 
26             fx=3;
27         if(fx==2&&i==j)   
28             fx=4;
29         if(fx==3&&(i+j==n+1))
30             fx=2;
31         if(fx==4&&(i+j==n+1))
32             fx=1;
33         if(fx==1)
34         {
35             ++j;
36             a[i][j]=now;
37             now++;
38             tot++;
39         }
40         if(fx==2)
41         {
42             --j;
43             a[i][j]=now;
44             now++;
45             tot++;
46         }
47         if(fx==3)
48         {
49             --i;
50             a[i][j]=now;
51             now++;
52             tot++;
53         }
54         if(fx==4)
55         {
56             ++i;
57             a[i][j]=now;
58             now++;
59             tot++;
60         }
61     }
62     for(int i=1;i<=n;++i)
63     {
64         for(int j=1;j<=n;++j)
65         {
66             printf("%d ",a[i][j]);
67             if((i+j==n+1)||(i==j))
68                 ans+=a[i][j];
69         }
70         printf("\n");
71     }
72     printf("%d",ans);
73     return 0;
74 }

 

 

 

转载于:https://www.cnblogs.com/Mary-Sue/p/9138429.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值