Problem:


ぐるぐる模様

「ぐるぐる模様」を表示するプログラムを作成することにしました。「ぐるぐる模様」は以下のようなものとします。

1 辺の長さが n の場合、n 行 n 列の文字列として表示する。

左下隅を基点とし，時計回りに回転する渦状の模様とする。

線のある部分は #（半角シャープ）、空白部分は " "（半角空白）で表現する。

線と線の間は空白を置く。

整数 n を入力とし，1 辺の長さが n の「ぐるぐる模様」を出力するプログラムを作成してください。

Input

入力は以下の形式で与えられます。

d
n1
n2
:
nd

１行目にデータセットの数 d (d ≤ 20)、続く d 行に i 個目のぐるぐる模様の辺の長さ ni (1 ≤ ni ≤ 100) がそれぞれ１行に与えられます。

Output

データセットごとに、ぐるぐる模様を出力してください。データセットの間に１行の空行を入れてください。

Sample Input

2
5
6

Output for the Sample Input 

#####
#   #
# # #
# # #
# ###

######
#    #
# ## #
# #  #
# #  #
# ####



Sample input:
2
5
6


Sample output:
#####
#   #
# # #
# # #
# ###

######
#    #
# ## #
# #  #
# #  #
# ####

Submission status: Wrong Answer

Solution code:
vector = ((0, -1), (1, 0), (0, 1), (-1, 0))

def make_guruguru(d):
  lst = [["#"] * (d + 4)]
  for _ in range(d + 2):
    lst.append(["#"] + [" "] * (d + 2) + ["#"])
  lst.append(["#"] * (d + 4))
  x, y = 2, d + 1
  lst[y][x] = "#"
  direct = 0
  vx, vy = vector[0]
  cnt = 1
  while True:
    while lst[y + vy * 2][x + vx * 2] == " ":
      lst[y + vy][x + vx] = "#"
      y += vy
      x += vx
      cnt += 1
    if cnt <= 1:
      break
    direct = (direct + 1) % 4
    vx, vy = vector[direct]
    cnt = 0
  for y in range(2, d + 2):
    print("".join(lst[y][2:-2]))
  print()
  for line in lst:
    print("".join(line))

n = int(input())
for _ in range(n):
  d = int(input())
  make_guruguru(d)

Submission status: Wrong Answer

Solution code:
for _ in [0]*input():
  n = input()
  A = [list(' '*n) for _ in [0]*n]
  for i in range((n+3)/4):
    i2 = i*2
    if i2>0: A[n-i2][i2]='@'
    for j in range(i2, n-i2):
      A[j][i2]='@'
      A[i2][j]='@'
      if j<n-i2-1: A[j][n-i2-1]='@'
      if j>i2+1: A[n-i2-1][j]='@'
  for e in A: print "".join(e)
  print

Submission status: Wrong Answer

Solution code:
def f(n):
    spiral = [list(' ' for i in range(n)) for i in range(n)]
    for i in range(n):
        spiral[i][0] = '#'
    for i in range(n):
        spiral[0][i] = '#'
    for i in range(n):
        spiral[i][-1] = '#'
        
    return spiral
        
def draw(n, m):
    #down
    for w in range(m, n):
        spiral[n-1][w] = '#'
    if n-m == 2:
        return
    #left
    for h in range(m, n):
        spiral[h][m] = '#'
    if n-m == 3:
        return
    #up
    for w in range(m, n-2):
        spiral[m][w] = '#'
    if n-m == 4:
        return
    #right
    for h in range(m, n-2):
        spiral[h][n-3] = '#'
    if n-m == 5:
        return
        
    draw(n-2, m+2)

c = 0
for i in range(input()):
    if c != 0:
        print
    n = input()
    if n == 1:
        spiral = [['#']]
    elif n == 2:
        spiral = [['#'],['#']]
    elif 3 <= n:
        spiral = f(n)
    if 4 <= n:
        draw(n, 2)
    for line in spiral:
        print ''.join(line)
    c = 1

Submission status: Wrong Answer

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

"""
import sys
from sys import stdin
input = stdin.readline
from itertools import cycle


def guruguru(n):
    if n < 5:
        return

    line = 0
    dirs = cycle([(0, -1), (1, 0), (0, 1), (-1, 0)])

    M = [[' '] * n for _ in range(n)]
    cx = 0
    cy = n - 1

    while line < n:
        line += 1
        dx, dy = dirs.__next__()
        while True:
            M[cy][cx] = '#'
            nx = cx + dx
            ny = cy + dy
            nnx = nx + dx
            nny = ny + dy

            if nx < 0 or nx >= n:
                break
            if ny < 0 or ny >= n:
                break
            if nny < 0 or nny >= n or nnx < 0 or nnx >= n:
                pass
            else:
                if M[nny][nnx] != ' ':
                    break
            cx = nx
            cy = ny

    for l in M:
        print(''.join(map(str, l)))


def main(args):
    n = int(input())
    for _ in range(n):
        size = int(input())
        guruguru(size)


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

Submission status: Wrong Answer

Solution code:
for r in range(input()):
	if r > 0: print
	n = input()
	if n < 3:
		for i in range(n): print "#"
		continue
	S = [[" "]*n for i in range(n)]
	x,y,dx,dy = 0,n-1,0,-1
	while 1:
		S[y][x] = "#"
		y += dy; x += dx
		try:
			if y+dy == -1: raise
			if S[y+dy][x+dx] == "#":
				y -= dy; x -= dx
				raise
		except:
			S[y][x] = "#"
			dx,dy = -dy,dx
			y += dy; x += dx
		if S[y+dy][x+dx] == "#" or S[y+dx][x-dy] == "#": break
	for i in range(n):
		print "".join(S[i])

Submission status: Accepted

Solution code:
vector = ((0, -1), (1, 0), (0, 1), (-1, 0))

def make_guruguru(d):
  lst = [["#"] * (d + 4)]
  for _ in range(d + 2):
    lst.append(["#"] + [" "] * (d + 2) + ["#"])
  lst.append(["#"] * (d + 4))
  x, y = 2, d + 1
  lst[y][x] = "#"
  direct = 0
  vx, vy = vector[0]
  cnt = 1
  while True:
    while lst[y + vy * 2][x + vx * 2] == " ":
      lst[y + vy][x + vx] = "#"
      y += vy
      x += vx
      cnt += 1
    if cnt <= 1:
      break
    direct = (direct + 1) % 4
    vx, vy = vector[direct]
    cnt = 0
  for y in range(2, d + 2):
    print("".join(lst[y][2:-2]))

n = int(input())
make_guruguru(int(input()))
for _ in range(n - 1):
  print()
  make_guruguru(int(input()))

Submission status: Accepted

Solution code:
for c in range(input()):
  n = input()
  A = [list(' '*n) for _ in [0]*n]
  for i in range((n+3)/4):
    i2 = i*2
    if i2>0: A[n-i2][i2]='#'
    for j in range(i2, n-i2):
      A[j][i2]='#'
      A[i2][j]='#'
      if j<n-i2-1: A[j][n-i2-1]='#'
      if j>i2+1: A[n-i2-1][j]='#'
  if c: print
  for e in A: print "".join(e)

Submission status: Accepted

Solution code:
s="#"
for c in range(input()):
  n = input()
  A = [list(' '*n) for _ in [0]*n]
  for i in range((n+3)/4):
    i2 = i*2
    if i2>0: A[n-i2][i2]=s
    for j in range(i2, n-i2):
      A[j][i2]=s
      A[i2][j]=s
      if j<n-i2-1: A[j][n-i2-1]=s
      if j>i2+1: A[n-i2-1][j]=s
  if c: print
  for e in A: print "".join(e)

Submission status: Accepted

Solution code:
def f(n):
    spiral = [list(' ' for i in range(n)) for i in range(n)]
    for i in range(n):
        spiral[i][0] = '#'
    for i in range(n):
        spiral[0][i] = '#'
    for i in range(n):
        spiral[i][-1] = '#'
        
    return spiral
        
def draw(n, m):
    #down
    for w in range(m, n):
        spiral[n-1][w] = '#'
    if n-m == 2:
        return
    #left
    for h in range(m, n):
        spiral[h][m] = '#'
    if n-m == 3:
        return
    #up
    for w in range(m, n-2):
        spiral[m][w] = '#'
    if n-m == 4:
        return
    #right
    for h in range(m, n-2):
        spiral[h][n-3] = '#'
    if n-m == 5:
        return
        
    draw(n-2, m+2)

c = 0
for i in range(input()):
    if c != 0:
        print
    n = input()
    if n == 1:
        spiral = [['#']]
    elif n == 2:
        spiral = [['##'],['# ']]
    elif 3 <= n:
        spiral = f(n)
    if 4 <= n:
        draw(n, 2)
    for line in spiral:
        print ''.join(line)
    c = 1

Submission status: Accepted

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

"""
import sys
from sys import stdin
input = stdin.readline
from itertools import cycle


def guruguru(n):
    line = 0
    dirs = cycle([(0, -1), (1, 0), (0, 1), (-1, 0)])

    M = [[' '] * n for _ in range(n)]
    cx = 0
    cy = n - 1

    while line < n:
        line += 1
        dx, dy = dirs.__next__()
        while True:
            M[cy][cx] = '#'
            nx = cx + dx
            ny = cy + dy
            nnx = nx + dx
            nny = ny + dy

            if nx < 0 or nx >= n:
                break
            if ny < 0 or ny >= n:
                break
            if nny < 0 or nny >= n or nnx < 0 or nnx >= n:
                pass
            else:
                if M[nny][nnx] != ' ':
                    break
            cx = nx
            cy = ny

    for l in M:
        print(''.join(map(str, l)))


def main(args):
    n = int(input())
    for i in range(n):
        size = int(input())
        guruguru(size)
        if i != (n - 1):
            print()


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

Submission status: Accepted

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

"""
import sys
from sys import stdin
input = stdin.readline
from itertools import cycle


def guruguru(n):
    dirs = cycle([(0, -1), (1, 0), (0, 1), (-1, 0)]) #  x, y???????????? (???????????????????????????)

    M = [[' '] * n for _ in range(n)] #  ??????????????¨?????????????????§?????????
    cx = 0                      #  ??????????????°???
    cy = n - 1
    line = 0                    #  ???????????§??????????????????n??¨???????????°??????????????¨??????

    while line < n:
        line += 1
        dx, dy = dirs.__next__() #  ???????????????????????????????????????????????????
        while True:
            M[cy][cx] = '#'
            nx = cx + dx        #  ?¬???????????????¨???????????????
            ny = cy + dy
            nnx = nx + dx       #  ?¬?????¬???????????????¨???????????????
            nny = ny + dy

            if nx < 0 or nx >= n: #  ??????????????????????????????????????§???????????¢?????????
                break
            if ny < 0 or ny >= n:
                break
            if nny < 0 or nny >= n or nnx < 0 or nnx >= n:
                pass
            else:
                if M[nny][nnx] != ' ': #  ??????????????????????????????????????¢??????????????????????????£??????????????´??????????????¢?????????
                    break
            cx = nx
            cy = ny

    # ?????????????????????????????????
    for l in M:
        print(''.join(l))


def main(args):
    n = int(input())
    for i in range(n):
        size = int(input())
        guruguru(size)
        if i != (n - 1):        #  ????????\?????????????????????????????????????????\??????
            print()


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

Submission status: Accepted

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

"""
import sys
from sys import stdin
input = stdin.readline
from itertools import cycle


def guruguru(n):
    dirs = cycle([(0, -1), (1, 0), (0, 1), (-1, 0)]) #  x, y???????????? (???????????????????????????)

    M = [[' '] * n for _ in range(n)] #  ??????????????¨?????????????????§?????????
    cx = 0                      #  ??????????????°???
    cy = n - 1
    line = 0                    #  ???????????§??????????????????n??¨???????????°??????????????¨??????

    while line < n:
        line += 1
        dx, dy = dirs.__next__() #  ???????????????????????????????????????????????????
        while True:
            M[cy][cx] = '#'

            nx = cx + dx        #  ?¬???????????????¨???????????????
            ny = cy + dy
            if not 0 <= nx < n: #  ??????????????????????????????????????§???????????¢?????????
                break
            if not 0 <= ny < n:
                break
            nnx = nx + dx       #  ?¬?????¬???????????????¨???????????????
            nny = ny + dy
            if 0 <= nny < n and 0 <= nnx < n:
                if M[nny][nnx] != ' ': #  ??????????????????????????????????????¢??????????????????????????£??????????????´??????????????¢?????????
                    break
            cx = nx
            cy = ny

    # ?????????????????????????????????
    for l in M:
        print(''.join(l))


def main(args):
    n = int(input())
    for i in range(n):
        size = int(input())
        guruguru(size)
        if i != (n - 1):        #  ????????\?????????????????????????????????????????\??????
            print()


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

Submission status: Accepted

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

"""
import sys
from sys import stdin
input = stdin.readline


M = []
def guruguru(n):
    global M
    dirs = [(0, -1), (1, 0), (0, 1), (-1, 0)] #  x, y???????????? (???????????????????????????)

    M = [[' '] * n for _ in range(n)] #  ??????????????¨?????????????????§?????????
    cx = 0                      #  ??????????????°???
    cy = n - 1
    line = 0                    #  ???????????§??????????????????n??¨???????????°??????????????¨??????

    while line < n:
        dx, dy = dirs[line % 4]
        line += 1
        while True:
            M[cy][cx] = '#'

            nx = cx + dx        #  ?¬???????????????¨???????????????
            if not 0 <= nx < n: #  ??????????????????????????????????????§???????????¢?????????
                break
            ny = cy + dy
            if not 0 <= ny < n:
                break
                
            nnx = nx + dx       #  ?¬?????¬???????????????¨???????????????
            nny = ny + dy
            if 0 <= nny < n and 0 <= nnx < n:
                if M[nny][nnx] != ' ': #  ??????????????????????????????????????¢??????????????????????????£??????????????´??????????????¢?????????
                    break
            cx = nx
            cy = ny

    # ?????????????????????????????????
    for l in M:
        print(''.join(l))


def main(args):
    n = int(input())
    for i in range(n):
        size = int(input())
        guruguru(size)
        if i != (n - 1):        #  ????????\?????????????????????????????????????????\??????
            print()


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

Submission status: Accepted

Solution code:
def p(t):
    for r in t:
        for c in r:
            print(c,end="")
        print("")
        
a = int(input())
for j in range(a):
    n = int(input())
    t = [ [ " " for _ in range(n) ] for _ in range(n)]
    d = 1 # 0:up, 1:right, 2:down, 3:left

    for i in range(n):
        t[i][0] = "#"

    x = 0
    y = 0
    for m in range(n-1):
        l = n - 1 - (m//2)*2
        for i in range(l):
            if d == 0:
                y -= 1
            elif d == 1:
                x += 1
            elif d == 2:
                y += 1
            elif d == 3:
                x -= 1
                
            t[y][x] = "#"

        d = (d + 1) % 4
    p(t)
    if j != a-1:
        print("")

Submission status: Accepted

Solution code:
class Vector:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def move(self, offset):
        self.x += offset[0]
        self.y += offset[1]

    def move_offset(self, offset, multiple=1):
        x = self.x + offset[0] * multiple
        y = self.y + offset[1] * multiple
        return Vector(x, y)


NOTHING = " "
EXIST = "#"
SENTINEL = "?"

MOVE = [
    [[-1, -1], [-1, +0], [-1, +1]],
    [[-1, +1], [-0, +1], [+1, +1]],
    [[+1, +1], [+1, +0], [+1, -1]],
    [[+1, -1], [+0, -1], [-1, -1]],
]


def create_area(size):
    area = [[SENTINEL] * 2 + [NOTHING] * size + [SENTINEL] * 2 for _ in range(size)]
    tmp = [[SENTINEL] * size + [SENTINEL] * 2 * 2]
    area = tmp * 2 + area + tmp * 2
    return area


def even_spiral_pattern(area, point):
    move_index = 0
    area[point.x][point.y] = EXIST

    while True:

        left, center, right = MOVE[move_index]
        end1, end2 = point.move_offset(left), point.move_offset(right)
        offset, offset2 = point.move_offset(center), point.move_offset(center, 2)

        if area[end1.x][end1.y] == EXIST or area[end2.x][end2.y] == EXIST:
            return area
        elif area[offset.x][offset.y] == NOTHING and area[offset2.x][offset2.y] != EXIST:
            point.move(center)
            area[point.x][point.y] = EXIST
        else:
            move_index += 1
            move_index %= 4


def odd_spiral_pattern(area, point):
    move_index = 0
    is_end = False
    area[point.x][point.y] = EXIST

    while True:

        left, center, right = MOVE[move_index]
        offset, offset2 = point.move_offset(center), point.move_offset(center, 2)

        if area[offset.x][offset.y] == NOTHING and area[offset2.x][offset2.y] != EXIST:
            point.move(center)
            area[point.x][point.y] = EXIST
            is_end = False
        else:
            if is_end:
                return area
            else:
                is_end = True

            move_index += 1
            move_index %= 4


def formater(area):
    output = ["".join(item).replace(SENTINEL, "") for item in result[2:-2]]
    output = "\n".join(output)
    return output


output = []

for _ in range(int(input())):
    size = int(input())

    area = create_area(size)
    point = Vector(size - 1 + 2, 2)

    if size % 2 == 0:
        result = even_spiral_pattern(area, point)
    else:
        result = odd_spiral_pattern(area, point)

    output.append(formater(result))

print("\n\n".join(output))

Submission status: Accepted

Solution code:
class Vector:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def move(self, offset):
        self.x += offset[0]
        self.y += offset[1]

    def move_offset(self, offset, multiple=1):
        x = self.x + offset[0] * multiple
        y = self.y + offset[1] * multiple
        return Vector(x, y)


class Pattern:
    NOTHING = " "
    EXIST = "#"
    SENTINEL = "?"

    MOVE = [
        [[-1, -1], [-1, +0], [-1, +1]],
        [[-1, +1], [-0, +1], [+1, +1]],
        [[+1, +1], [+1, +0], [+1, -1]],
        [[+1, -1], [+0, -1], [-1, -1]],
    ]

    @classmethod
    def create_area(cls, size):
        area = [[cls.SENTINEL] * 2 + [cls.NOTHING] * size + [cls.SENTINEL] * 2 for _ in range(size)]
        tmp = [[cls.SENTINEL] * size + [cls.SENTINEL] * 2 * 2]
        area = tmp * 2 + area + tmp * 2
        return area

    @classmethod
    def even_spiral_pattern(cls, area, point):
        move_index = 0
        area[point.x][point.y] = cls.EXIST

        while True:

            left, center, right = cls.MOVE[move_index]
            end1, end2 = point.move_offset(left), point.move_offset(right)
            offset, offset2 = point.move_offset(center), point.move_offset(center, 2)

            if area[end1.x][end1.y] == cls.EXIST or area[end2.x][end2.y] == cls.EXIST:
                return area
            elif area[offset.x][offset.y] == cls.NOTHING and area[offset2.x][offset2.y] != cls.EXIST:
                point.move(center)
                area[point.x][point.y] = cls.EXIST
            else:
                move_index += 1
                move_index %= 4

    @classmethod
    def odd_spiral_pattern(cls, area, point):
        move_index = 0
        is_end = False
        area[point.x][point.y] = cls.EXIST

        while True:

            left, center, right = cls.MOVE[move_index]
            offset, offset2 = point.move_offset(center), point.move_offset(center, 2)

            if area[offset.x][offset.y] == cls.NOTHING and area[offset2.x][offset2.y] != cls.EXIST:
                point.move(center)
                area[point.x][point.y] = cls.EXIST
                is_end = False
            else:
                if is_end:
                    return area
                else:
                    is_end = True

                move_index += 1
                move_index %= 4

    @classmethod
    def formater(cls, area):
        output = ["".join(item).replace(cls.SENTINEL, "") for item in area[2:-2]]
        output = "\n".join(output)
        return output

    @classmethod
    def solve(cls, size):
        area = cls.create_area(size)
        point = Vector(size - 1 + 2, 2)

        if size % 2 == 0:
            result = cls.even_spiral_pattern(area, point)
        else:
            result = cls.odd_spiral_pattern(area, point)

        return cls.formater(result)


sizes = [int(input()) for _ in range(int(input()))]
results = [Pattern.solve(num) for num in sizes]
print("\n\n".join(results))

Submission status: Accepted

Solution code:
class Vector:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def move(self, offset):
        self.x += offset[0]
        self.y += offset[1]

    def move_offset(self, offset, multiple=1):
        x = self.x + offset[0] * multiple
        y = self.y + offset[1] * multiple
        return Vector(x, y)


class Pattern:
    NOTHING = " "
    EXIST = "#"
    SENTINEL = "?"

    MOVE = [
        [[-1, -1], [-1, +0], [-1, +1]],
        [[-1, +1], [-0, +1], [+1, +1]],
        [[+1, +1], [+1, +0], [+1, -1]],
        [[+1, -1], [+0, -1], [-1, -1]],
    ]

    @classmethod
    def create_area(cls, size):
        area = [[cls.SENTINEL] * 2 + [cls.NOTHING] * size + [cls.SENTINEL] * 2 for _ in range(size)]
        tmp = [[cls.SENTINEL] * size + [cls.SENTINEL] * 2 * 2]
        area = tmp * 2 + area + tmp * 2
        return area

    @classmethod
    def even_spiral_pattern(cls, area, point):
        move_index = 0
        area[point.x][point.y] = cls.EXIST

        while True:

            left, center, right = cls.MOVE[move_index]
            end1, end2 = point.move_offset(left), point.move_offset(right)
            offset, offset2 = point.move_offset(center), point.move_offset(center, 2)

            if area[end1.x][end1.y] == cls.EXIST or area[end2.x][end2.y] == cls.EXIST:
                return area
            elif area[offset.x][offset.y] == cls.NOTHING and area[offset2.x][offset2.y] != cls.EXIST:
                point.move(center)
                area[point.x][point.y] = cls.EXIST
            else:
                move_index += 1
                move_index %= 4

    @classmethod
    def odd_spiral_pattern(cls, area, point):
        move_index = 0
        is_end = False
        area[point.x][point.y] = cls.EXIST

        while True:

            left, center, right = cls.MOVE[move_index]
            offset, offset2 = point.move_offset(center), point.move_offset(center, 2)

            if area[offset.x][offset.y] == cls.NOTHING and area[offset2.x][offset2.y] != cls.EXIST:
                point.move(center)
                area[point.x][point.y] = cls.EXIST
                is_end = False
            else:
                if is_end:
                    return area
                else:
                    is_end = True

                move_index += 1
                move_index %= 4

    @classmethod
    def formater(cls, area):
        output = ["".join(item[2:-2]) for item in area[2:-2]]
        output = "\n".join(output)
        return output

    @classmethod
    def solve(cls, size):
        area = cls.create_area(size)
        point = Vector(size - 1 + 2, 2)

        if size % 2 == 0:
            result = cls.even_spiral_pattern(area, point)
        else:
            result = cls.odd_spiral_pattern(area, point)

        return cls.formater(result)


sizes = [int(input()) for _ in range(int(input()))]
results = [Pattern.solve(num) for num in sizes]
print("\n\n".join(results))

Submission status: Accepted

Solution code:
# AOJ 0141 Spiral Pattern
# Python3 2018.6.23 bal4u

for ci in range(int(input())):
	if ci > 0: print()
	n = int(input())
	a = [[' ' for c in range(n+5)] for c in range(n+5)]
	for r in range(0, n+4, n+3):
		for c in range(n+4): a[r][c] = '#'
	for c in range(0, n+4, n+3):
		for r in range(n+4): a[r][c] = '#'
	r, c = n+1, 2
	a[r][c] = '#'
	d = 'U'
	stop = 0
	while 1:
		if stop >= 4: break
		if d == 'U':
			if a[r-2][c] == '#' or a[r-1][c] == '#' or a[r-1][c+1] == '#':
				d = 'R'
				stop += 1
			else:
				r -= 1
				a[r][c] = '#'
				stop = 0
		if d == 'R':
			if a[r][c+2] == '#' or a[r][c+1] == '#' or a[r+1][c+1] == '#':
				d = 'D'
				stop += 1
			else:
				c += 1
				a[r][c] = '#'
				stop = 0
		if d == 'D':
			if a[r+2][c] == '#' or a[r+1][c] == '#' or a[r+1][c-1] == '#':
				d = 'L'
				stop += 1
			else:
				r += 1
				a[r][c] = '#'
				stop = 0
		if d == 'L':
			if a[r][c-2] == '#' or a[r][c-1] == '#' or a[r-1][c-1] == '#':
				d = 'U'
				stop += 1
			else:
				c -= 1
				a[r][c] = '#'
				stop = 0
	for r in range(2, n+2):	print(*a[r][2:n+2], sep='')

Submission status: Accepted

Solution code:
mv=((0,-1),(1,0),(0,1),(-1,0))

def check(x,y,di):
    mx=x+mv[di%4][0]
    my=y+mv[di%4][1]
    for tx,ty in mv:
        if my+ty==y and mx+tx==x:
            continue
        if L[my+ty][mx+tx]=="#":
            return False
    return True

d=input()
for p in range(d):
    n=input()
    L=[[" "]*(n+4) for i in range(n+4)]
    for i in range(n+4):
        L[0][i]=L[i][0]=L[n+3][i]=L[i][n+3]="#"
    x,y,di=2,n+1,0
    while n!=0:
        while check(x,y,di):
            L[y][x]="#"
            x+=mv[di%4][0]
            y+=mv[di%4][1]
        else:
            L[y][x]="#"
        di+=1
        n-=1
    for i in range(2,len(L)-2):
        print "".join(L[i][2:-2])
    if p!=d-1:
        print

Submission status: Accepted

Solution code:
D = [[-1,0],[0,1],[1,0],[0,-1]]
def s(N):
    used = [[False]*N+[True] for _ in xrange(N)]+[[True]*(N+1)]
    ret = [[" "]*N for _ in xrange(N)]
    q = [(0,N-1,0)]
    used[N-1][0] = used[N-1][1] = True
    while len(q) != 0:
        d,y,x = q.pop(0)
        ret[y][x] = "#"
        sy,sx = D[d]
        ry,rx = D[(d+1)%4]
        if not used[y+sy][x+sx]:
            q.append((d,y+sy,x+sx))
            used[y+sy][x+sx] = used[y+ry][x+rx] = True
        elif not used[y+ry][x+rx]:
            q.append(((d+1)%4,y+ry,x+rx))
            used[y+ry][x+rx] = True
    return ret

n = input()
while True:
    n -= 1
    N = input()    
    print "\n".join(map(lambda a:"".join(a),s(N)))
    if n == 0:
        break
    print

Submission status: Accepted

Solution code:
D = [[-1,0],[0,1],[1,0],[0,-1]]
def s(N):
    used = [[False]*N+[True] for _ in xrange(N)]+[[True]*(N+1)]
    ret = [[" "]*N for _ in xrange(N)]
    d,y,x = 0,N-1,0
    used[N-1][0] = used[N-1][1] = True
    while True:
        ret[y][x] = "#"
        sy,sx = D[d]
        ry,rx = D[(d+1)%4]
        if not used[y+sy][x+sx]:
            used[y+sy][x+sx] = used[y+ry][x+rx] = True
            d,y,x = d,y+sy,x+sx
        elif not used[y+ry][x+rx]:
            used[y+ry][x+rx] = True
            d,y,x = (d+1)%4,y+ry,x+rx
        else:
            break
    return ret

n = input()
while True:
    n -= 1
    N = input()    
    print "\n".join(map(lambda a:"".join(a),s(N)))
    if n == 0:
        break
    print

Submission status: Accepted

Solution code:
D = [[-1,0],[0,1],[1,0],[0,-1]]
def s(N):
    used = [[False]*N+[True] for _ in xrange(N)]+[[True]*(N+1)]
    ret = [[" "]*N for _ in xrange(N)]
    d,y,x = 0,N-1,0
    used[N-1][0] = used[N-1][1] = True
    while True:
        ret[y][x] = "#"
        fy,fx = D[d]
        ry,rx = D[(d+1)%4]
        if not used[y+fy][x+fx]:
            used[y+fy][x+fx] = used[y+ry][x+rx] = True
            d,y,x = d,y+fy,x+fx
        elif not used[y+ry][x+rx]:
            used[y+ry][x+rx] = True
            d,y,x = (d+1)%4,y+ry,x+rx
        else:
            break
    return ret

n = input()
while True:
    n -= 1
    N = input()    
    print "\n".join(map(lambda a:"".join(a),s(N)))
    if n == 0:
        break
    print

Submission status: Accepted

Solution code:
for r in range(input()):
	if r > 0: print
	n = input()
	if n < 3:
		for i in range(n): print "#"*(n-i) + " "*i
		continue
	S = [[" "]*n for i in range(n)]
	x,y,dx,dy = 0,n-1,0,-1
	while 1:
		S[y][x] = "#"
		y += dy; x += dx
		try:
			if S[y+dy][x+dx] == "#":
				if y+dy != -1:
					y -= dy; x -= dx
				raise
		except:
			S[y][x] = "#"
			dx,dy = -dy,dx
			y += dy; x += dx
		if S[y+dy][x+dx] == "#" or S[y+dx][x-dy] == "#": break
	for i in range(n):
		print "".join(S[i])

Submission status: Accepted

Solution code:
dd = ((-1, 0), (0, -1), (1, 0), (0, 1))

d = int(input())
for i in range(d):
    if i:
        print()
    N = int(input())
    MP = [[" "]*N for i in range(N)]
    for i in range(N):
        MP[i][0] = "#"
    def walk(x, y, d, n):
        dx, dy = dd[d % 4]
        for k in range(n):
            x += dx; y += dy
            MP[y][x] = "#"
        return x, y
    x = y = 0
    r = N-1; d = 2
    while r > 1:
        x, y = walk(x, y, d, r)
        x, y = walk(x, y, d+1, r)
        r -= 2; d += 2
    if r == 1:
        walk(x, y, d, r)
    for line in MP:
        print(*line, sep='')

Submission status: Runtime Error

Solution code:
for _ in [0]*input():
  n = input()
  A = [list(' '*n) for _ in [0]*n]
  for i in range((n+3)/4):
    i2 = i*2
    if i2>0: A[n-i2][i2]='@'
    for j in range(i2, n-i2):
      A[j][i2]='@' #左下→左上
      A[i2][j]='@' #左上→右上
      if j<n-i2-1: A[j][n-i2-1]='@' #右上→右下
      if j>i2+1: A[n-i2-1][j]='@' #右下→左下下
  for e in A: print "".join(e)
  print

Submission status: Runtime Error

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

"""
import sys
from sys import stdin
input = stdin.readline
from itertools import cycle


def guruguru(n):
    if n < 5:
        return

    line = 0
    dirs = cycle([(0, -1), (1, 0), (0, 1), (-1, 0)])

    M = [[' '] * n for _ in range(n)]
    cx = 0
    cy = n - 1

    while line < n:
        line += 1
        dx, dy = dirs.__next__()
        while True:
            M[cy][cx] = '#'
            nx = cx + dx
            ny = cy + dy
            nnx = nx + dx
            nny = ny + dy

            if nx < 0 or nx >= n:
                break
            if ny < 0 or ny >= n:
                break
            if nny < 0 or nny >= n or nnx < 0 or nnx >= n:
                pass
            else:
                if M[nny][nnx] != ' ':
                    break
            cx = nx
            cy = ny

    for l in M:
        print(''.join(map(str, l)))


def main(args):
    for line in sys.stdin:
        n = int(line)
        guruguru(n)


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

Submission status: Runtime Error

Solution code:
for r in range(input()):
	if r > 0: print
	n = input()
	S = [[" "]*n for i in range(n)]
	x,y,dx,dy = 0,n-1,0,-1
	while 1:
		S[y][x] = "#"
		y += dy; x += dx
		try:
			if y+dy == -1: raise
			if S[y+dy][x+dx] == "#":
				y -= dy; x -= dx
				raise
		except:
			S[y][x] = "#"
			dx,dy = -dy,dx
			y += dy; x += dx
		if S[y+dy][x+dx] == "#" or S[y+dx][x-dy] == "#": break
	for i in range(n):
		print "".join(S[i])

Submission status: WA: Presentation Error

Solution code:
for _ in [0]*input():
  n = input()
  A = [list(' '*n) for _ in [0]*n]
  for i in range((n+3)/4):
    i2 = i*2
    if i2>0: A[n-i2][i2]='#'
    for j in range(i2, n-i2):
      A[j][i2]='#'
      A[i2][j]='#'
      if j<n-i2-1: A[j][n-i2-1]='#'
      if j>i2+1: A[n-i2-1][j]='#'
  for e in A: print "".join(e)
  print

Submission status: WA: Presentation Error

Solution code:
def f(n):
    spiral = [list(' ' for i in range(n)) for i in range(n)]
    for i in range(n):
        spiral[i][0] = '#'
    for i in range(n):
        spiral[0][i] = '#'
    for i in range(n):
        spiral[i][-1] = '#'
        
    return spiral
        
def draw(n, m):
    #down
    for w in range(m, n):
        spiral[n-1][w] = '#'
    if n-m == 2:
        return
    #left
    for h in range(m, n):
        spiral[h][m] = '#'
    if n-m == 3:
        return
    #up
    for w in range(m, n-2):
        spiral[m][w] = '#'
    if n-m == 4:
        return
    #right
    for h in range(m, n-2):
        spiral[h][n-3] = '#'
    if n-m == 5:
        return
        
    draw(n-2, m+2)

c = 0
for i in range(input()):
    if c != 0:
        print
    n = input()
    if n == 1:
        spiral = [['#']]
    elif n == 2:
        spiral = [['##'],['#']]
    elif 3 <= n:
        spiral = f(n)
    if 4 <= n:
        draw(n, 2)
    for line in spiral:
        print ''.join(line)
    c = 1