1160 蛇形矩阵

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

代码简单,看看就懂。


代码:

#include <stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

int ans[111][111];
int main()
{
    int n;
    scanf("%d",&n);
    int x = n / 2 + 1, y = n / 2 + 1, c = 1;
    ans[x][y++] = 1;
    for( int i = 2; i <= n * n; )
    {
        if( i * i > c ) c += 2;
        ans[x][y] = i++;
        for( int j = 1; j <= c - 2; j++ ) ans[--x][y] = i++;
        for( int j = 1; j <= c - 1; j++ ) ans[x][--y] = i++;
        for( int j = 1; j <= c - 1; j++ ) ans[++x][y] = i++;
        for( int j = 1; j <= c - 1; j++ ) ans[x][++y] = i++;
        y++;
    }
    c = 0;
    for( int i = 1; i <= n; i++ )
        for( int j = 1; j <= n; j++ )
        {
            if( i == j || i + j == n + 1 ) c += ans[i][j];
            printf( "%d%c", ans[i][j], j == n ? '\n' : ' ' );
        }
    printf("%d\n",c);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值