1. 程式人生 > >python實現棋盤覆蓋演算法

python實現棋盤覆蓋演算法

# coding:utf-8

# 定義陣列寬度為2的幾次方
k = 2
# 棋盤寬度
size1 = pow(2, k)
# L形塊的初始值
mark = 0
# table初始化
table = [[-1 for x in range(size1)] for y in range(size1)]


def chess(tr, tc, pr, pc, size):
    global mark
    global table
    if size == 1:
        return
    mark += 1
    count = mark
    half = size // 2
    if pr < tr + half and pc < tc + half:
        chess(tr, tc, pr, pc, half)
    else:
        table[tr + half - 1][tc + half - 1] = count
        chess(tr, tc, tr + half - 1, tc + half - 1, half)
    if pr < tr + half and pc >= tc + half:
        chess(tr, tc + half, pr, pc, half)
    else:
        table[tr + half - 1][tc + half] = count
        chess(tr, tc + half, tr + half - 1, tc + half, half)
    if pr >= tr + half and pc < tc + half:
        chess(tr + half, tc, pr, pc, half)
    else:
        table[tr + half][tc + half - 1] = count
        chess(tr + half, tc, tr + half, tc + half - 1, half)
    if pr >= tr + half and pc >= tc + half:
        chess(tr + half, tc + half, pr, pc, half)
    else:
        table[tr + half][tc + half] = count
        chess(tr + half, tc + half, tr + half, tc + half, half)


# 棋盤展示
def show(t):
    n = len(t)
    for i in range(n):
        for j in range(n):
            print "% 4d" % t[i][j],
        print


chess(0, 0, 1, 1, size1)
show(table)