在乙個 個方格組成的棋盤中,有乙個方格與其它的不同,使用四種l型骨牌覆蓋除這個特殊方格的其它方格,請使用分治法實現棋盤覆蓋
<1>分析:
由於原棋盤只有乙個特殊方格,我們首先將棋盤規格從 減少一半分割為4個 子棋盤(a)所示,這4個子棋盤中只有乙個子棋盤包含該特殊方格,其餘3個子棋盤中沒有特殊方格。為了將這3個沒有特殊方格的子棋盤轉化為特殊棋盤,以便採用遞迴方法求解,可以用乙個l型骨牌覆蓋這3個較小棋盤的會合處,如圖(b)所示,從而將原問題轉化為4個較小規模的棋盤覆蓋問題。遞迴地使用這種劃分策略,直至將棋盤分割為1×1的子棋盤。
def chess(tr,tc,pr,pc,size):#tr:棋盤初始行號 tc:棋盤初始列號
#pr:特殊棋盤格行號 pc:特殊棋盤格列號
#size:棋盤格大小
global mark
global table
if size==1:
return #遞迴終止條件
mark+=1 #表示直角骨牌號
count=mark
half=size//2 #當size不等於1時,棋盤格規模減半,變為4個
#小棋盤格進行遞迴操作
#左上角
if (pr=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)
#將[tr+half-1,tc+half]作為小規模棋盤格的特殊點,進行遞迴
#左下角
if (pr>=tr+half) and (pc=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)
#將[tr+half,tc+half]作為小規模棋盤格的特殊點,進行遞迴
#輸出矩陣
def show(table):
n=len(table)
for i in range(n):
for j in range(n):
print(table[i][j],end=' ')
print('')
mark=0
n=8 #輸入8*8的棋盤規格
table=[[-1 for x in range(n)] for y in range(n)] #-1代表特殊格仔
chess(0,0,2,2,n) #特殊棋盤位置
show(table)
棋盤覆蓋問題python3實現
在2 k 2 k個方格組成的棋盤中,有乙個方格被占用,用下圖的4種l型骨牌覆蓋所有棋盤上的其餘所有方格,不能重疊。如下 def chess tr,tc,pr,pc,size global mark global table mark 1 count mark if size 1 return hal...
棋盤覆蓋問題python3實現
在2 k 2 k個方格組成的棋盤中,有乙個方格被占用,用下圖的4種l型骨牌覆蓋全部棋盤上的其餘全部方格,不能重疊。例如以下 def chess tr,tc,pr,pc,size global mark global table mark 1 count mark if size 1 return h...
棋盤覆蓋問題
source code include include include using namespace std const int n 1024 int board n n count void cover int sx,int sy,int cx,int cy,int size,int cx1,i...