Magic Odd Square (Codeforces 710C)
Tags: Math, constructive algorithms

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.


Sample Inputs:
1

3

Sample Outputs:
1

2 1 4
3 5 7
6 9 8

Solution (Python):
n = int(input())
cube = [[0 for _ in range(n)] for _ in range(n)]
cube[0][(n + 1) // 2 - 1] = 1
idx = [0, (n + 1) // 2 - 1]
for i in range(2, n * n + 1):
    if idx[0] == 0:
        if idx[1] != n - 1:
            idx = [n - 1, idx[1] + 1]
        else:
            idx = [1, n - 1]
    elif idx[1] == n - 1:
        idx = [idx[0] - 1, 0]
    elif cube[idx[0] - 1][idx[1] + 1] == 0:
        idx = [idx[0] - 1, idx[1] + 1]
    else:
        idx = [idx[0] + 1, idx[1]]
    cube[idx[0]][idx[1]] = i
for i in range(n):
    for j in range(n):
        print(cube[i][j], end=' ')
    print()

Solution (Python):
(q, n) = ([-1, 0], int(input()))
for i in range(n):
    r = ''
    for j in range(n):
        k = min(abs(i - n // 2), abs(j - n // 2)) % 2
        q[k] += 2
        r += str(q[k]) + ' '
    print(r)

Solution (Python):
(q, n) = ([-1, 0], int(input()))
for i in range(n):
    r = ''
    for j in range(n):
        k = min(abs(i - n // 2), abs(j - n // 2)) % 2
        q[k] += 2
        r += str(q[k]) + ' '
    print(r)