Problem:


魔方陣

 n × n の正方形のマス目の中に数字の１から n × n  が一つずつ入っていて、縦のどの列のマス目の和も、横のどの列のマス目の和も対角線のマス目の和も等しいものを魔方陣といいます。

一辺のマスの個数が奇数の魔方陣の作り方には以下の方法があります。

中央のマス目のちょうど一つ下のマス目に１を入れる。

次の数字を右斜め下のマス目に入れる。
ただし、数字を入れようとしたマス目が正方形からはみ出している場合、すでに数字が埋まっている場合は以下の方法に従って数字を入れるマス目を探す。

右にはみ出した場合には、同じ行の左はしに、左にはみ出した場合には、同じ行の右はしに、下にはみ出した場合には、同じ列の一番上に数字を入れる。

 数字を入れようとしたマス目が埋まっているときには、その埋まっているマス目の左斜め下のマス目に入れる。

全てのマス目が埋まるまで２を繰り返す。

この方法に従って、一辺のマス目の個数 n を入力として、その大きさの魔方陣を出力するプログラムを作成して下さい。ただし、n は 3 以上 15 以下の奇数とします。マス目に入る各数字は右詰 4 桁で出力してください。

入力

複数の入力が与えられます。各入力で n （正の整数）が１行に与えられます。入力は 0 で終了します。入力の数は 10 を超えません。

出力

各入力に対して n × n の魔方陣を出力して下さい。

Sample Input

3
5
0

Output for the Sample Input

   4   9   2
   3   5   7
   8   1   6
  11  24   7  20   3
   4  12  25   8  16
  17   5  13  21   9
  10  18   1  14  22
  23   6  19   2  15



Sample input:
3
5
0


Sample output:
   4   9   2
   3   5   7
   8   1   6
  11  24   7  20   3
   4  12  25   8  16
  17   5  13  21   9
  10  18   1  14  22
  23   6  19   2  15

Submission status: Wrong Answer

Solution code:
while True:
    n = int(raw_input())
    if n == 0:
        break
    magic = [[0 for i in range(n)] for i in range(n)]
    x, y = n/2, n/2
    magic[y][x] = 1
    count = 2
    while count <= n**2:
        x, y = (x+1)%n, (y+1)%n
        if magic[y][x] == 0:
            magic[y][x] = count
            count += 1
        else:
            x, y = (x-1)%n, (y+1)%n
            magic[y][x] = count
            count += 1
    for i in xrange(n):
        print "".join(map(lambda s:str(s).rjust(4),magic[i]))

Submission status: Accepted

Solution code:
import sys
for n in map(int, sys.stdin):
    if not n:
        break
    a = [[-1]*(n+2)]+[[-1]+[0]*n+[-1] for _ in [0]*n]+[[-1]*(n+2)]
    x, y = (n+1)//2, (n+1)//2+1
    for i in range(1, n**2+1):
        while a[y][x]:
            if a[y][x] == -1:
                if x in {0, n+1}:
                    x = (1, n)[x==0]
                if y in {0, n+1}:
                    y = (1, n)[y==0]
            else:
                x, y = x-1, y+1
        a[y][x] = i
        x, y = x+1, y+1

    for l in a[1:-1]:
        print("".join(map(lambda x: "{:>4d}".format(x), l[1:-1])))

Submission status: Accepted

Solution code:
while True:
	n = input()
	if n == 0: break
	board = [[0] * n for i in range(n)]
	xp = n / 2
	yp = n / 2 + 1
	for i in range(n ** 2):
		if board[yp][xp] == 0:
			board[yp][xp] = i + 1
		else:
			xp -= 1
			yp += 1
			if xp == -1: xp = n - 1
			if yp == n : yp = 0
			board[yp][xp] = i + 1
		yp += 1
		xp += 1
		if xp == n: xp = 0
		if yp == n: yp = 0
	for b in board:
		print "".join(map(lambda x:str("% 4d" % x), b))

Submission status: Accepted

Solution code:
def chekend(mc):
    for m in mc:
        if not all(m):
            return False
    return True


def solve(n):
    mc = [ [ 0 for j in xrange(n) ] for i in xrange(n)]
    px = n/2
    py = n/2 + 1
    cnt = 1
    mc[py][px] = cnt
    px += 1
    py += 1
    cnt += 1
    while True:
        if chekend(mc): break
        if px >= n: px = 0; continue
        if px < 0: px = n-1; continue
        if py >= n: py = 0; continue
        if mc[py][px]: px -= 1; py += 1; continue
        mc[py][px] = cnt
        cnt += 1
        px += 1
        py += 1

    for m in mc:
        line = ""
        for l in m:
            line += "%4d"%(l)
        print line
while True:
    n = input()
    if n == 0:
        break
    solve(n)

Submission status: Accepted

Solution code:
import sys
f = sys.stdin

def set1(sq):
    x = len(sq) // 2
    y = len(sq) // 2 + 1
    square[y][x] = 1
    return x, y, 1
def mv_r(sq, x, y):
    x = (x + 1) % len(sq)
    y = (y + 1) % len(sq)
    return x, y
def mv_l(sq, x, y):
    x -= 1
    if x < 0:
        x += len(sq)
    y = (y + 1) % len(sq)
    return x, y

def setnext(sq, x, y, i):
    x, y = mv_r(sq, x,y)
    i += 1
    while sq[y][x]:
        x, y = mv_l(sq, x, y)
    sq[y][x] = i
    return x, y, i

while True:
    n = int(f.readline())
    if n == 0:
        break
    square = [[None for j in range(n)] for i in range(n)]
    arg = set1(square)
    for i in range(n * n - 1):
        arg = setnext(square,*arg)

    for line in square:
        for num in line:
            print("{:4d}".format(num),end='')
        print()

Submission status: Accepted

Solution code:
import sys
while True:
    n=input()
    if n==0:
        break
    magic=[[0 for i in range(n)] for j in range(n)]
    i=n/2
    j=n/2+1
    for number in range(1,n*n+1):
        magic[j][i]=number
        if number==n*n:
            break
        if magic[(j+1)%n][(i+1)%n]==0:
            i,j=(i+1)%n,(j+1)%n
        else:
            i,j=(i+1)%n,(j+1)%n
            while magic[j][i]!=0:
                i,j=(i-1)%n,(j+1)%n
    for i in range(n):
        print "".join(["%4d" %(e) for e in magic[i]])

Submission status: Accepted

Solution code:
while True:
  n = int(input())
  if n==0:
    break
  else:
    l = [[0 for i in range(n)] for j in range(n)]
    x = n//2
    y = n//2+1
    c = 0
    while c < n**2:
      c += 1
      while l[y][x] != 0:
        y += 1
        if y >= n:
          y = 0
        x -= 1
        if x <= -1:
          x = n-1
      l[y][x] = c
      x += 1
      if x >= n:
        x = 0
      y += 1
      if y >= n:
        y = 0
    for i in l:
      a = ''
      for j in i:
        if 0 <= j < 10**1:
          a = a + '   ' + str(j)
        elif 10**1<=j<10**2:
          a = a + '  ' + str(j)
        elif 10**2<=j<10**3:
          a = a + ' ' + str(j)
      print(a)

Submission status: Accepted

Solution code:

while 1:
    n=int(raw_input())
    if n==0:
        break
    l=[[0]*n for i in range(n)]
    x,y=n/2,n/2+1
    l[y][x]=1
    cnt=2
    while cnt<=n**2:
        x,y=(x+1)%n,(y+1)%n
        if l[y][x]==0:
            l[y][x]=cnt
            cnt+=1
        else:
            x,y=(x-1)%n,(y+1)%n
            l[y][x]=cnt
            cnt+=1
    for i in range(n):
        print ''.join(map(lambda s:str(s).rjust(4),l[i]))

Submission status: Accepted

Solution code:
def check_space(y,x):
    if g[y][x]==-1:
        return True
    return False

while 1:
    n=int(raw_input())
    if n==0:break
    g=[[-1]*n for _ in xrange(n)]
    for i in xrange(1,n**2+1):
        if i==1:
            g[n/2+1][n/2]="1"
            nowy=n/2+1
            nowx=n/2
            continue
        while 1:
            if check_space((nowy+1)%n,(nowx+1)%n):
                g[(nowy+1)%n][(nowx+1)%n]=str(i)
                nowy=(nowy+1)%n
                nowx=(nowx+1)%n
                break
            else:
                nowy=(nowy+1)%n
                nowx=(nowx-1)%n
                continue
    for i in xrange(n):
        tmp=""
        for j in xrange(n):
            tmp+=g[i][j].rjust(4)
        print(tmp)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

import sys
import os
import math

for s in sys.stdin:
    n = int(s)
    if n == 0:
        break

    M = [[None for i in range(n)] for j in range(n)]

    # 1
    x = n // 2
    y = n // 2 + 1
    M[y][x] = 1
    x = x + 1
    y = y + 1
    counter = 2

    while counter < n * n + 1:

        if x >= n:
            x = 0
        elif x < 0:
            x = n - 1

        if y >= n:
            y = 0
        elif y < 0:
            y = n - 1

        if M[y][x] is not None:
            x -= 1
            y += 1
        else:
            M[y][x] = counter
            counter += 1
            x += 1
            y += 1

    for row in M:
        for v in row:
            print(str(v).rjust(4), end='')
        print()

Submission status: Accepted

Solution code:
from sys import stdin
def sqmatrix(n):
  return [[0] * n for i in range(n)]

def magicsq(m):
    n = len(m)
    j = int(n/2)
    i = j + 1
    for num in range(1, n**2 + 1):
        m[i][j] = num
        i += 1
        j += 1
        i = i%n
        j = j % n
        if m[i][j] != 0:
            i += 1
            j -= 1
        if j < 0:
            j = n -1
        i = i % n
    return m

for line in stdin:
    n = int(line)
    if n == 0:
        break
    sm = sqmatrix(n)
    for row in magicsq(sm): print (''.join(map(lambda x: str(x).rjust(4, ' '),row)))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0078
"""
import sys



class MagicSquare():
    def __init__(self, size):
        self.size = size
        self.data = [['@']*self.size for _ in range(self.size)]
        self.fill_data()

    def fill_data(self):
        num = 1
        x = self.size // 2
        y = x + 1
        self.data[y][x] = num

        while num < self.size**2:
            x += 1
            if x >= self.size:
                x = 0
            y += 1
            if y >= self.size:
                y = 0
            if self.data[y][x] == '@':
                num += 1
                self.data[y][x] = num
            else:
                while self.data[y][x] != '@':
                    x -= 1
                    if x < 0:
                        x = self.size - 1
                    y += 1
                    if y >= self.size:
                        y = 0
                num += 1
                self.data[y][x] = num

    def print_data(self):
        for row in self.data:
            temp = ""
            for d in row:
                temp += str(d).rjust(4)
            print(temp)
            temp = ""



def main(args):
    while True:
        size = int(input())
        if size < 3 or size%2 == 0:
            break
        ms = MagicSquare(size)
        ms.print_data()


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Accepted

Solution code:
# Aizu Problem 0078: Magic Square
#
import sys, math, os

# read input:
PYDEV = os.environ.get('PYDEV')
if PYDEV=="True":
    sys.stdin = open("sample-input.txt", "rt")


def magic_square(n):
    sq = [[0 for _ in range(16)] for __ in range(16)]
    nowx, nowy = n // 2, n // 2 + 1
    sq[nowy][nowx] = 1
    for i in range(2, n**2 + 1):
        nowx += 1
        nowy += 1
        while True:
            if nowx >= n:
                nowx = 0
            if nowx < 0:
                nowx = n - 1
            if nowy >= n:
                nowy = 0
            if sq[nowy][nowx] != 0:
                nowx -= 1
                nowy += 1
            if sq[nowy][nowx] == 0 and 0 <= nowx and nowx < n and 0 <= nowy and nowy < n:
                break
        sq[nowy][nowx] = i
    return sq[:n]

while True:
    n = int(input())
    if n == 0:
        break
    sq = magic_square(n)
    for row in sq:
        out = ""
        for k in row[:n]:
            ks = str(k)
            ks = ' ' * (4 - len(ks)) + ks
            out += ks
        print(out)

Submission status: Accepted

Solution code:
def magic_square(n):
    a = [[0 for i in range(n)] for j in range(n)]

    x = n//2
    y = (n+1)//2
    i = 1
    while True:
        if a[y][x] == 0:
            a[y][x] = i
            i += 1
            x += 1
            y += 1
        else:
            x -= 1
            y += 1
            
        if x >= n:
            x = 0
        elif x < 0:
            x = n-1
        if y >= n:
            y = 0
        
        if i > (n*n):
            break
    return a

def print_square(a):
    for aa in a:
        for aaa in aa:
            print('{0:4d}'.format(aaa),end="")
        print('')

while True:
    n = int(input())
    if n == 0:
        break
    else:
        a = magic_square(n)
        print_square(a)

Submission status: Accepted

Solution code:
def fprint(x):
    if x < 10:
        print("   ",end="")
    elif x < 100:
        print("  ",end="")
    elif x < 1000:
        print(" ",end="")
    print(x,end="")

while True:
    N = int(input())
    if N == 0:
        break

    table = [[0 for i in range(N)] for j in range(N)]

    cnt =  1
    row = N // 2 + 1
    col = N // 2
    table[row][col] = cnt
    while cnt < N*N:
        row = (row + 1) % N
        col = (col + 1) % N
        while table[row][col] != 0:
            row = (row + 1) % N
            col = (col - 1 + N) % N
        cnt += 1
        table[row][col] = cnt

    for i in range(N):
        for j in range(N):
            fprint(table[i][j])
        print("")

Submission status: Accepted

Solution code:
def check_range(xy, n):
    for i in range(2):
        if xy[i] == -1:
            xy[i] = n - 1
        elif xy[i] == n:
            xy[i] = 0
    return xy

while True:
    n = int(input())
    if n == 0:
        break
    ms = [[0 for i in range(n)] for j in range(n)]
    xy = [n//2, n//2 - 1]
    i = 1
    while i <= n*n:
        if ms[xy[1]][xy[0]] != 0:
            xy[0] -= 1
            xy[1] -= 1
            xy = check_range(xy, n)
            continue
        ms[xy[1]][xy[0]] = i
        xy[0] += 1
        xy[1] -= 1
        xy = check_range(xy, n)
        i += 1
    for i in range(n):
        s = ""
        for j in range(n):
            s += "{0:>4}".format(str(ms[n - i - 1][j]))
        print(s)

Submission status: Accepted

Solution code:
for e in iter(input,'0'):
 n=int(e);m,f=[[0]*n for _ in[0]*n],'{:4}'*n
 j=n//2;i=j+1
 m[i][j]=1
 for k in range(2,n*n+1):
  i,j=-~i%n,-~j%n
  if m[i][j]:i,j=-~i%n,~-j%n
  m[i][j]=k
 for r in m:print(f.format(*r))

Submission status: Accepted

Solution code:
for e in iter(input,'0'):
 n=int(e);m,f=[[0]*n for _ in[0]*n],'{:4}'*n
 j=n//2;i=j+1
 m[i][j]=1
 for k in range(2,n*n+1):
  i,j,t=-~i%n,-~j%n,j
  if m[i][j]:i,j=-~i%n,t
  m[i][j]=k
 for r in m:print(f.format(*r))

Submission status: Accepted

Solution code:
for e in iter(input,'0'):
 n=int(e);m,f=[[0]*n for _ in[0]*n],'{:4}'*n
 s=lambda x:-~x%n
 j=n//2;i=j+1
 m[i][j]=1
 for k in range(2,n*n+1):
  i,j,t=s(i),s(j),j
  if m[i][j]:i,j=s(i),t
  m[i][j]=k
 for r in m:print(f.format(*r))

Submission status: Accepted

Solution code:
def square(n):
  mp = [[0 for _ in range(n)] for _ in range(n)]
  
  x, y = n // 2 , n // 2 + 1
  mp[y][x] = 1
  
  for i in range(2, n ** 2 + 1):
    x = (x + 1) % n
    y = (y + 1) % n
    
    while mp[y][x]:
      y = (y + 1) % n
      x = (x - 1) % n
    
    mp[y][x] = i
  
  for line in mp:
    s = ""    
    for i in line:
      si = str(i)
      s += si.rjust(4)
    print(s)

while True:
  n = int(input())
  if not n:
    break
  square(n)

Submission status: Accepted

Solution code:
while 1:
    n=int(input())
    if n==0:break
    c=1
    nx=ny=int((n-1)/2)
    b=[[0 for _ in range(n)] for _ in range(n)]
    ny=ny+1
    b[ny][nx]=c

    for _ in range(n*n-1):
        c+=1
        nx+=1
        ny+=1
        while 1:
            if 0<=nx<=n-1 and 0<=ny<=n-1 and b[ny][nx]==0:
                break
            if nx>n-1:
                nx=0
            if nx<0:
                nx=n-1
            if ny>n-1:
                ny=0
            if b[ny][nx]==0:
                break
            else:
                nx-=1
                ny+=1
        b[ny][nx]=c
    for i in b:
        print(("".join([str(l).rjust(4) for l in i])))

Submission status: Accepted

Solution code:
# AOJ 0078 Magic Square
# Python3 2018.6.17 bal4u

MAX = 15

tbl = [0]*MAX
while True:
	n = int(input())
	if n == 0: break
	tbl = [[0 for r in range(n)] for c in range(n)]
	r, c = n//2+1, n//2
	tbl[r][c] = i = 1
	while i < n*n:
		r += 1
		c += 1
		while True:
			if c >= n: c = 0;
			elif c < 0: c = n - 1;
			if r >= n: r = 0;
			if tbl[r][c] == 0:
				i += 1
				tbl[r][c] = i
				break
			r += 1
			c -= 1

	for r in range(n):
		for c in range(n):
			print(format(tbl[r][c], '4d'), end='')
		print()

Submission status: Accepted

Solution code:
ans = []
while True:
    n = input()
    if n == 0:
        break
    c = 1
    N = n*n
    circle = [0]*N
    p = (N+1)/2-1
    while c <= N:
        if p == N:
            p = 1
        elif p % n == 0:
            p += 1
        elif p+n > N:
            p -= (N-n-1)
        else:
            p += n+1
        
        if circle[p-1] != 0:
            while circle[p-1] != 0:
                if p == N-n+1:
                    p = n
                elif p-1 % n == 0:
                    p += (n*2 -1)
                elif p+n > N:
                    p -= N - n + 1
                else:
                    p += n-1

        circle[p-1] = c
        c += 1
    p = 0
    temp = ''
    while p*n != N:
        temp += ''.join(map(lambda x:str(x).rjust(4),circle[n*p:n*(p+1)]))
        temp += '\n'
        p += 1
    ans.append(temp.rstrip())
for i in ans:
    print i

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# coding: utf-8


def table_to_string(table):
    lines = []
    for row in table:
        line = ""
        for num in row:
            line += "% 4d" % num
        lines.append(line)
    return "\n".join(lines)


def get_answer(n):
    table = [[0 for i in xrange(n)] for j in xrange(n)]
    x = (n - 1) / 2
    y = (n - 1) / 2 + 1
    for i in xrange(1, n * n + 1):
        while 1:
            if x == n:
                x = 0
            elif x == -1:
                x = n - 1
            if y == n:
                y = 0
            if table[y][x]:
                x -= 1
                y += 1
                continue
            else:
                break
        table[y][x] = i
        x += 1
        y += 1
    return table_to_string(table)


def main():
    params = []
    while 1:
        param = int(raw_input())
        if not param:
            break
        params.append(param)

    for param in params:
        print get_answer(param)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
while True:
    n=input()
    if n==0:
        break
    board=[[0]*n for unused in xrange(n)]
    y,x=n/2+1,n/2
    board[y][x]=1
    for i in xrange(2,n*n+1):
        ny,nx=(y+1)%n,(x+1)%n
        while True:
            if board[ny][nx]==0:
                y,x=ny,nx
                break
            else:
                ny,nx=(ny+1)%n,(nx+n-1)%n
        board[y][x]=i
        
    for i in xrange(n):
        print "".join(map(lambda s:str(s).rjust(4),board[i]))

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, absolute_import, print_function,
                        unicode_literals)
from sys import stdin


def solve(n):
    square = [[0]*n for _ in range(n)]
    x = n // 2
    y = x + 1

    square[y][x] = 1
    for i in range(1, n*n):
        x = (x+1) % n
        y = (y+1) % n
        if square[y][x]:
            x = (x-1) % n
            y = (y+1) % n
        square[y][x] = i + 1

    fmt = ('{:4d}' * n).format
    print('\n'.join(fmt(*row) for row in square))

for line in stdin:
    n = int(line)
    if not n:
        break
    solve(n)

Submission status: Accepted

Solution code:
while True:
    n = int(raw_input())
    if n == 0:
        break
    magic = [[0 for i in range(n)] for i in range(n)]
    x, y = n/2, n/2+1
    magic[y][x] = 1
    count = 2
    while count <= n**2:
        x, y = (x+1)%n, (y+1)%n
        if magic[y][x] == 0:
            magic[y][x] = count
            count += 1
        else:
            x, y = (x-1)%n, (y+1)%n
            magic[y][x] = count
            count += 1
    for i in xrange(n):
        print "".join(map(lambda s:str(s).rjust(4),magic[i]))

Submission status: Accepted

Solution code:
def magic(n):
    c=1
    x=n/2
    y=x+1
    while 1:
        A[y][x]=c
        if c==n*n:break
        while 1:
            x,y=(x+1)%n,(y+1)%n
            if A[y][x]==0:break
            x,y=(x-1)%n,(y+1)%n
            if A[y][x]==0:break
        c+=1
    return
while 1:
    n=input()
    if n==0:break
    N=range(n)
    A=[[0]*n for i in N]
    magic(n)
    for i in N:
        print "".join(["%4d"%(A[i][j])for j in N])

Submission status: Accepted

Solution code:
def magic(n):
    c=1
    x=n/2
    y=x+1
    while 1:
        A[y][x]=c
        if c==n*n:break
        while 1:
            x,y=(x+1)%n,(y+1)%n
            if A[y][x]==0:break
            x,y=(x-1)%n,(y+1)%n
            if A[y][x]==0:break
        c+=1
    return
while 1:
    n=input()
    if n==0:break
    N=range(n)
    A=[[0]*n for i in N]
    magic(n)
    for i in N:
        print "".join(["%4d"%(e)for e in A[i]])

Submission status: Accepted

Solution code:
def f(x,y):
    while 1:
        x,y=(x+1)%n,(y+1)%n
        if A[y][x]==0:break
        x,y=(x-1)%n,(y+1)%n
        if A[y][x]==0:break
    return x,y

def magic(n):
    c=1
    x=n/2
    y=x+1
    while 1:
        A[y][x]=c
        if c==n*n:break
        x,y=f(x,y)
        c+=1
    return

while 1:
    n=input()
    if n==0:break
    N=range(n)
    A=[[0]*n for i in N]
    magic(n)
    for i in N:
        print "".join(["%4d"%(e)for e in A[i]])

Submission status: Accepted

Solution code:
def magic(n):
    c=1
    x=n/2
    y=x+1
    while 1:
        A[y][x]=c
        if c==n*n:break
        while 1:
            x,y=(x+1)%n,(y+1)%n
            if A[y][x]==0:break
            x,y=(x-1)%n,(y+1)%n
            if A[y][x]==0:break
        c+=1
    return
while 1:
    n=input()
    if n==0:break
    N=range(n)
    A=[[0]*n for i in N]
    magic(n)
    for i in N:
        print "".join(["%4d" %(e)for e in A[i]])

Submission status: Accepted

Solution code:
while 1:
    n = input()
    if n == 0:
        break
    field = [[0] * n for _ in xrange(n)]
    cnt = 1
    x, y = n / 2, n / 2 + 1
    field[y][x] = cnt
    cnt += 1
    while cnt <= n ** 2:
        y = (y + 1) % n
        x = (x + 1) % n
        while field[y][x] > 0:
            y = (y + 1) % n
            x = (x - 1 + n) % n
        field[y][x] = cnt
        cnt += 1

    for i in xrange(n):
        print ''.join(map("{0:4}".format, field[i]))

Submission status: Accepted

Solution code:
while 1:
    n = int(input())
    if n == 0:
        break
    l = [[ 0 for i in range(n)] for j in range(n)]

    i = n//2 + 1
    j = n//2
    l[i][j] = '   1'
    c = 2
    d = '{: >4}'.format(c)


    for x in range(n**2 - 1):
        i = (i + 1) % n
        j = (j + 1) % n
        while l[i][j] != 0:
            i = (i + 1) % n
            j = (j - 1) % n
        l[i][j] = d
        c += 1
        d = '{: >4}'.format(c)

    for s in range(n):
        print(*l[s],sep="")

Submission status: Accepted

Solution code:
while True :
    n = int(input())
    if n == 0 :
        break
    
    magic = list([0] * n for i in range(n))
    x = (n+1)//2 - 1
    y = (n+1)//2 - 2
    for i in range(1, n**2+1) :
        x += 1
        y += 1
        while True :
            if x >= n :
                x = 0
            if y >= n :
                y = 0
            if magic[x][y] != 0 :
                x += 1
                y -= 1
                if y == -1 :
                    y = n - 1
            if x < n and y < n and magic[x][y] == 0 :
                break
        magic[x][y] = i
        
    for i in range(n) :
        for j in range(n) :
            print('{:4}'.format(magic[i][j]), end="")
        print()

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
    N = int(readline())
    if N == 0:
        return False
    x = N//2; y = x+1
    P = [[-1]*N for i in range(N)]
    c = 0
    N2 = N*N
    while c < N2:
        if P[y][x] == -1:
            c += 1
            P[y][x] = c
            x = (x + 1) % N; y = (y + 1) % N
        else:
            x = (x - 1) % N; y = (y + 1) % N
    for line in P:
        write("".join(map("{:4d}".format, line)))
        write("\n")
    return True
while solve():
    ...

Submission status: Accepted

Solution code:
def print_board(A,n):
	for i in range(n):
		s = ""
		for j in range(n):
			st = str(A[i][j])
			if len(st) == 1:
				s += "   "
			elif len(st) == 2:
				s += "  "
			elif len(st) == 3:
				s += " "

			s += str(st)
		print(s)


def check_leftdown(A,h,w,n):
	if h + 1 > n - 1:
		#下に抜けるならば,左に-1してその列に値が入っていない箇所を探す
		w -= 1

		for x in range(n):
			if A[x][w] == 0:
				h = x
				break

	else:
		#左に抜けるならば
		if w - 1 < 0:
			w = n
			h += 1
		else:
			h += 1
			w -= 1

	return h,w

def check_rightdown(A,h,w,n):
	if h + 1 > n - 1:

		#下にも右にも抜ける場合
		if w + 1 > n - 1:
			None
		else:
			#下に抜けるならば,右に＋1してその列に値が入っていない箇所を探す
			w += 1

		for x in range(n):
			if A[x][w] == 0:
				h = x
				break

	else:
		if w + 1 > n - 1:
		#右に抜けるならば
			w = 0
			h += 1
		else:
			#通常パターン
			h += 1
			w += 1
			if A[h][w] != 0:
				#値が既に埋まっている
				#左下をチェック
				h,w = check_leftdown(A,h,w,n)

	return h,w

if __name__ == '__main__':

	while True:
		try:
			n = int(input())

			if n == 0:
				break

			A = [[0 for i in range(n)] for j in range(n)]

			cnt = n * n
			for x in range(cnt):
				if x == 0:
					mid = n // 2
					h = mid + 1
					w = mid
					A[h][w] = x + 1
				else:
					h,w = check_rightdown(A,h,w,n)
					A[h][w] = x+1

			print_board(A,n)

		except EOFError:
			break

Submission status: Accepted

Solution code:
def square(n):
    mp = [[0 for _ in range(n)] for _ in range(n)]

    x, y = n // 2, n // 2 + 1
    mp[y][x] = 1

    for i in range(2, n ** 2 + 1):
        x = (x + 1) % n
        y = (y + 1) % n

        while mp[y][x]:
            y = (y + 1) % n
            x = (x - 1) % n

        mp[y][x] = i

    for line in mp:
        s = ""
        for i in line:
            si = str(i)
            s += si.rjust(4)
        print(s)


while True:
    n = int(input())
    if not n:
        break
    square(n)

Submission status: Accepted

Solution code:
while 1:
    n=int(input())
    if n==0:break
    ans=[[0 for i in range(n)] for j in range(n)]
    y=n//2
    x=n//2-1
    for i in range(1,n**2+1):
        y=[y+1,y+1-n][y+1==n]
        x=[x+1,x+1-n][x+1==n]
        if ans[y][x]==0:ans[y][x]=str(i).rjust(4)
        else:
            y=[y+1,y+1-n][y+1==n]
            x=[x-1,x-1+n][x==0]
            ans[y][x]=str(i).rjust(4)
    for i in ans:print(''.join(map(str,i)))

Submission status: Accepted

Solution code:
def fill(x,y,count):
    global board
    if count == n**2:
        return 0
    count += 1
    while board[x%n][y%n] != 0:
        x += 1
        y -= 1
    board[x%n][y%n] = count
    fill(x+1,y+1,count)

    
while(1):
    n = int(input())
    if n == 0:
        break
    board = [[0 for i in range(n)] for j in range(n)]
    fill(int(n/2)+1,int(n/2),0)
    board = [["{: >4}".format(i) for i in j] for j in board]
    [print(*board[i],sep="") for i in range(n)]

Submission status: Runtime Error

Solution code:
from sys import stdin
def sqmatrix(n):
  return [[0] * n for i in range(n)]

def magicsq(m):
    n = len(m)
    j = n/2
    i = j + 1
    for num in range(1, n**2 + 1):
        m[i][j] = num
        i += 1
        j += 1
        i = i%n
        j = j % n
        if m[i][j] != 0:
            i += 1
            j -= 1
        if j < 0:
            j = n -1
        i = i % n
    return m

for line in stdin:
    n = int(line)
    if n == 0:
        break
    sm = sqmatrix(n)
    for row in magicsq(sm): print (' '.join(map(str,row)))

Submission status: Runtime Error

Solution code:
while True:
    n = int(raw_input())
    if n == 0:
        break
    magic = [[0 for i in range(n)] for i in range(n)]
    x, y = n/2, n/2
    magic[y][x] = 1
    count = 2
    while count <= n**2:
        x, y = (x+1)%n, (y+1)%n
        if magic[y][x] == 0:
            magic[y][x] = count
            count += 1
        else:
            x, y = (x-1)%n, (y+1)%n
            magic[y][x] = count
            count += 1
    for i in xrange(n):
        print "".join(map(lambda s:str(s).rjust(4),board[i])

Submission status: WA: Presentation Error

Solution code:
while True:
	n = input()
	if n == 0: break
	board = [[0] * n for i in range(n)]
	xp = n / 2
	yp = n / 2 + 1
	for i in range(n ** 2):
		if board[yp][xp] == 0:
			board[yp][xp] = i + 1
		else:
			xp -= 1
			yp += 1
			if xp == -1: xp = n - 1
			if yp == n : yp = 0
			board[yp][xp] = i + 1
		yp += 1
		xp += 1
		if xp == n: xp = 0
		if yp == n: yp = 0
	for b in board:
		print " ".join(map(str, b))

Submission status: WA: Presentation Error

Solution code:
def chekend(mc):
    for m in mc:
        if not all(m):
            return False
    return True


def solve(n):
    mc = [ [ 0 for j in xrange(n) ] for i in xrange(n)]
    px = n/2
    py = n/2 + 1
    cnt = 1
    mc[py][px] = cnt
    px += 1
    py += 1
    cnt += 1
    while True:
        if chekend(mc): break
        if px >= n: px = 0; continue
        if px < 0: px = n-1; continue
        if py >= n: py = 0; continue
        if mc[py][px]: px -= 1; py += 1; continue
        mc[py][px] = cnt
        cnt += 1
        px += 1
        py += 1

    for m in mc:
        for l in m:
            print l,
        print
while True:
    n = input()
    if n == 0:
        break
    solve(n)

Submission status: WA: Presentation Error

Solution code:
def chekend(mc):
    for m in mc:
        if not all(m):
            return False
    return True


def solve(n):
    mc = [ [ 0 for j in xrange(n) ] for i in xrange(n)]
    px = n/2
    py = n/2 + 1
    cnt = 1
    mc[py][px] = cnt
    px += 1
    py += 1
    cnt += 1
    while True:
        if chekend(mc): break
        if px >= n: px = 0; continue
        if px < 0: px = n-1; continue
        if py >= n: py = 0; continue
        if mc[py][px]: px -= 1; py += 1; continue
        mc[py][px] = cnt
        cnt += 1
        px += 1
        py += 1

    for m in mc:
        for l in m:
            print "%4d"%(l),
        print
while True:
    n = input()
    if n == 0:
        break
    solve(n)

Submission status: WA: Presentation Error

Solution code:
def chekend(mc):
    for m in mc:
        if not all(m):
            return False
    return True


def solve(n):
    mc = [ [ 0 for j in xrange(n) ] for i in xrange(n)]
    px = n/2
    py = n/2 + 1
    cnt = 1
    mc[py][px] = cnt
    px += 1
    py += 1
    cnt += 1
    while True:
        if chekend(mc): break
        if px >= n: px = 0; continue
        if px < 0: px = n-1; continue
        if py >= n: py = 0; continue
        if mc[py][px]: px -= 1; py += 1; continue
        mc[py][px] = cnt
        cnt += 1
        px += 1
        py += 1

    for m in mc:
        for l in m:
            print "%3d"%(l),
        print
while True:
    n = input()
    if n == 0:
        break
    solve(n)

Submission status: WA: Presentation Error

Solution code:
import sys
f = sys.stdin

def set1(sq):
    x = len(sq) // 2
    y = len(sq) // 2 + 1
    square[y][x] = 1
    return x, y, 1
def mv_r(sq, x, y):
    x = (x + 1) % len(sq)
    y = (y + 1) % len(sq)
    return x, y
def mv_l(sq, x, y):
    x -= 1
    if x < 0:
        x += len(sq)
    y = (y + 1) % len(sq)
    return x, y

def setnext(sq, x, y, i):
    x, y = mv_r(sq, x,y)
    i += 1
    while sq[y][x]:
        x, y = mv_l(sq, x, y)
    sq[y][x] = i
    return x, y, i

while True:
    n = int(f.readline())
    if n == 0:
        break
    square = [[None for j in range(n)] for i in range(n)]
    arg = set1(square)
    for i in range(n * n - 1):
        arg = setnext(square,*arg)

    for line in square:
        print(*line)

Submission status: WA: Presentation Error

Solution code:
while True:
    n=input()
    if n==0:
        break
    magic=[[0 for i in range(n)] for j in range(n)]
    i=n/2
    j=n/2+1
    for number in range(1,n*n+1):
        magic[j][i]=number
        if number==n*n:
            break
        if magic[(j+1)%n][(i+1)%n]==0:
            i,j=(i+1)%n,(j+1)%n
        else:
            i,j=(i+1)%n,(j+1)%n
            while magic[j][i]!=0:
                i,j=(i-1)%n,(j+1)%n
    for i in range(n):
        for j in range(n):
            print str(magic[i][j]).rjust(4),
        print ""