[英]Knight's Tour only solvable for one size board
我正在嘗試在 python 中實現一個騎士的旅游查找器。 假設騎士必須從左上角開始(這里稱為 (0,0)),它會為 4x3 場找到一個解決方案,但不會為任何其他場找到解決方案。
def maneuvrability(position, path, width, height):
if position[0] < width and position[1] < height and position not in path and position[0] >= 0 and position[1] >= 0:
return True
else:
return False
def completedness(path,width,height):
if len(path) == (width*height):
return True
else:
return False
def possible_jumps(pos):
return_list = []
return_list.extend([
(pos[0]-1,pos[1]-2),
(pos[0]+1,pos[1]-2),
(pos[0]+2,pos[1]-1),
(pos[0]+2,pos[1]+1),
(pos[0]-1,pos[1]+2),
(pos[0]+1,pos[1]+2),
(pos[0]-2,pos[1]-1),
(pos[0]-2,pos[1]+1)])
return return_list
def knights_tour(width,height,path=[(0,0)]):
if completedness(path,width,height):
return path
else:
elem = path[len(path)-1]
succs = []
succs.extend(possible_jumps(elem))
for x in succs:
if maneuvrability(x,path,width,height):
return knights_tour(width,height,[y for y in path + [x]])
print(knights_tour(4,3))
print(knights_tour(5,5))
您的回溯不正確。 在每一步,您只檢查下一步是否有效,然后返回該移動是否導致騎士之旅。 相反,您需要修改代碼以檢查所有有效的移動,然后查看是否有任何移動導致了完整的騎士之旅。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.