您的位置:首页 > 其它

1160 蛇形矩阵

2017-08-14 09:38 246 查看
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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: