題目描述 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 ;
}
#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 ;
}