本文實(shí)例講述了Python3解決棋盤覆蓋問題的方法。分享給大家供大家參考,具體如下:
問題描述:
在2^k*2^k個(gè)方格組成的棋盤中,有一個(gè)方格被占用,用下圖的4種L型骨牌覆蓋所有棋盤上的其余所有方格,不能重疊。

代碼如下:
def chess(tr,tc,pr,pc,size):  global mark  global table  mark+=1  count=mark  if size==1:    return  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(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份,如果特殊格子在這個(gè)小棋盤中則繼續(xù)分成4份,如果不在這個(gè)小棋盤中就把該小棋盤中靠近中央的那個(gè)格子置位,表示L型骨牌的1/3占據(jù)此處,每一次遞歸都會(huì)遍歷查詢4個(gè)小棋盤,三個(gè)不含有特殊格子的棋盤置位的3個(gè)格子正好在大棋盤中央構(gòu)成一個(gè)完整的L型骨牌,依次類推,找到全部覆蓋方法。運(yùn)行結(jié)果如下:

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python加密解密算法與技巧總結(jié)》、《Python編碼操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選