接上一篇博客的问题:http://blog.csdn.net/zhang_xiaomeng/article/details/72954471
程序如下:
def cover(board, lab=1, top=0, left=0, side=None):
if side is None: side = len(board)
# Side length of subboard:
s = side // 2
# Offsets for outer/inner squares of subboards:
offsets = (0, -1), (side-1, 0)
for dy_outer, dy_inner in offsets:
for dx_outer, dx_inner in offsets:
# If the outer corner is not set...
if not board[top+dy_outer][left+dx_outer]:
# ... label the inner corner:
board[top+s+dy_inner][left+s+dx_inner] = lab
# Next label:
lab += 1
if s > 1:
for dy in [0, s]:
for dx in [0, s]:
# Recursive calls, if s is at least 2:
lab = cover(board, lab, top+dy, left+dx, s)
# Return the next available label:
return lab
运行:
>>> board = [[0]*8 for i in range(8)]
>>> board[7][7] = -1
>>> cover(board)
22
>>> for row in board:
print((" %2i"*8) % tuple(row))
3 3 4 4 8 8 9 9
3 2 2 4 8 7 7 9
5 2 6 6 10 10 7 11
5 5 6 1 1 10 11 11
13 13 14 1 18 18 19 19
13 12 14 14 18 17 17 19
15 12 12 16 20 17 21 21
15 15 16 16 20 20 21 -1
程序分析如下: