Codeforces 710C_Magic Odd Square(구성)

1518 단어 CodeForces
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 4
3 5 7

6 9 8
환방의 사상 구해, dfs로 검색:
#include
#include
#include
#include
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<

좋은 웹페이지 즐겨찾기