You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
# include <bits/stdc++.h>
using namespace std ;
const int N = 40 ;
int n ; //一个n*n的幻方
int g [ N ] [ N ] ; //一个二维数组用来存储幻方
int x , y ; //用来记录上一个位置
int main ( ) {
cin > > n ;
//1≤N≤39 且 N 为奇数。
//(1)首先, 将1写在第一行的中间
g [ 1 ] [ n / 2 + 1 ] = 1 ; // n/2+1, 是因为n是奇数噢,偶数不用+1
//记录上一个放置的位置【这个很重要,一定要记录上一次的位置!!!】
x = 1 ;
y = n / 2 + 1 ;
//尝试将2-n^2的数字放入 [核心思想:上一个位置]
for ( int i = 2 ; i < = n * n ; i + + ) {
if ( x = = 1 & & y ! = n ) g [ n ] [ y + 1 ] = i , x = n , y + + ;
else if ( y = = n & & x ! = 1 ) g [ x - 1 ] [ 1 ] = i , x - - , y = 1 ;
else if ( x = = 1 & & y = = n ) g [ 2 ] [ n ] = i , x = 2 ;
else if ( x ! = 1 & & y ! = n ) {
if ( g [ x - 1 ] [ y + 1 ] = = 0 ) g [ x - 1 ] [ y + 1 ] = i , x - - , y + + ;
else g [ x + 1 ] [ y ] = i , x + + ;
}
}
//输出
for ( int i = 1 ; i < = n ; i + + ) {
for ( int j = 1 ; j < = n ; j + + )
cout < < g [ i ] [ j ] < < " " ;
cout < < endl ;
}
return 0 ;
}