在2^k*2^k個方格組成的棋盤中,有一個方格被佔用,用的4種L型骨牌覆蓋所有棋盤上的其餘所有方格,不能重疊。
代碼如下:
def chess(tr,tc,pr,pc,size):global mark global tablemark+=1count=markif size==1:returnhalf=size//2if pr<tr+half and pc<tc+half:chess(tr,tc,pr,pc,half)else:table[tr+half-1][tc+half-1]=countchess(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]=countchess(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]=countchess(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]=countchess(tr+half,tc+half,tr+half,tc+half,half)def show(table):n=len(table)for i in range(n):for j in range(n):print(table[i][j],end='')print('')mark=0n=8table=[[-1 for x in range(n)] for y in range(n)]chess(0,0,2,2,n)show(table)
n是棋盤寬度,必須是2^k,本例中n=8,特殊格子在(2,2)位置,如所示:
採用分治法每次把棋盤分成4份,如果特殊格子在這個小棋盤中則繼續分成4份,如果不在這個小棋盤中就把該小棋盤中靠近中央的那個格子置位,表示L型骨牌的1/3佔據此處,每一次遞迴都會遍曆查詢4個小棋盤,三個不含有特殊格子的棋盤置位的3個格子正好在大棋盤中央構成一個完整的L型骨牌,依次類推,找到全部覆蓋方法。運行結果如下:
轉載請註明: