CodeForce 710C Magic Odd Square

Magic Odd Square

  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
题意:
  就是给一个奇数n,使n * n 的方格,行,列,主对角线相加为奇数。输出这样的正方形

思路:
  先在第一行中间放上1,然后向右上放数,有数了就放在当前的正下方,一直到结束。

AC代码:
 1 # include <bits/stdc++.h>
 2 using namespace std;
 3 const int MAX = 50;
 4 int a[MAX][MAX];
 5 bool vis[MAX][MAX];
 6 int main()
 7 {
 8     int n;
 9     scanf("%d", &n);
10     memset(vis, false, sizeof(vis));
11     a[1][n/2 + 1] = 1;
12     int r = 1;
13     int c = n/2 + 1;
14     vis[r][c] = true;
15     for(int i = 2; i <= n * n; i++)
16     {
17         int r1 = r;
18         int c1 = c;
19         r -= 1;
20         c += 1;
21         if(r < 1)
22             r = n;
23         if(c > n)
24             c = 1;
25         if(vis[r][c])
26         {
27             r = r1 + 1;
28             c = c1;
29         }
30         vis[r][c] = true;
31         a[r][c] = i;
32         
33     }
34     for(int i = 1; i <= n; i++)
35     {
36         for(int j = 1; j <= n; j++)
37         {
38             if(j == 1)
39                 cout << a[i][j];
40             else
41                 cout << " " << a[i][j];
42         }
43         cout << endl;
44     }
45     return 0;
46 }
View Code

 

 
posted @ 2016-08-23 10:15  stort  阅读(263)  评论(0编辑  收藏  举报