题目描述 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<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<bitset>
#include<iomanip>
using namespace std;
int map[ 105 ][ 105 ] ;
int main()
{
int n ;
cin >> n ;
for(long i = 0; i != n + 1 ; i++ )
{
map[ 0 ][ i ] = -1 ;
map[ n + 1 ][ i ] = -1 ;
map[ i ][ 0 ] = -1 ;
map[ i ][ n + 1 ] = -1;
}
long x = n , y = x ,d = 0;
long dir[ 4 ][ 2 ]={ { 0 , -1 },{ -1 , 0 },{ 0 , 1 },{ 1 , 0 }};
for(long i = n * n ; i >= 1 ; i-- )
{
map[ x ][ y ] = i;
x += dir[ d ][ 0 ];
y += dir[ d ][ 1 ];
if( map[ x ][ y ] != 0 )
{
x -= dir[ d ][ 0 ];
y -= dir[ d ][ 1 ];
d = ( d + 1 ) % 4 ;
x += dir[ d ][ 0 ];
y += dir[ d ][ 1 ];
}
}
for( int i = 1 ; i <= n ; ++i )
{
for( int j = 1 ; j <= n ; ++j )
cout << map[ i ][ j ] << " " ;
cout << endl ;
}
int ans = 0 ;
for( int i = 1 ; i <= n ; ++i )
{
ans += map[ i ][ i ] + map[ n - i + 1][ i ] ;
}
cout << ans - 1 << endl ;
return 0 ;
}