Codeforces 710C_Magic Odd Square(构造)

来源:互联网 发布:拔罐 菲尔普斯 知乎 编辑:程序博客网 时间:2024/05/29 18:10
C. Magic Odd Square
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.

Input

The only line contains odd integer n (1 ≤ n ≤ 49).

Output

Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.

Examples
input
1
output
1
input
3
output
2 1 43 5 7

6 9 8

幻方的思想求解,用dfs搜索:

#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;int ch[50][50];int n;void dfs(int x,int y,int v){    int x1,y1;    ch[x][y]=v;    if(x-1<1) x1=n;    else x1=x-1;    if(y+1>n) y1=1;    else y1=y+1;    if(ch[x1][y1]==0) {        dfs(x1,y1,v+1);    }    else {        if(x+1>n) x1=1;            else x1=x+1;        if(ch[x1][y]==0) {            dfs(x1,y,v+1);        }        else return ;    }}int main(){    cin>>n;    memset(ch,0,sizeof(ch));    dfs(1,n/2+1,1);    for(int i=1;i<=n;i++) {        for(int j=1;j<=n;j++) {            cout<<ch[i][j]<<" ";        }        cout<<endl;    }    return 0;}


0 0
原创粉丝点击