我一直试图连续两天解决这个问题,但我找不到有效的算法。给定一个棋盘和一些棋子,我必须检查所述棋盘是否可以被棋子游览,条件是每个棋子只能访问一个广场一次。我知道这是某种多重回溯,但我无法让它发挥作用。(我只能为个别作品实施一般骑士之旅)
tablero
是棋盘的一个类,它包含一个名称、一个棋子列表、一个包含禁止位置的列表、一个包含空闲位置的列表以及一个包含棋盘尺寸的元组。
ficha
是棋子的类,它包含一个名称nombre
(只前进 1)posicion
movimientos
欢迎任何见解。
这里是类(随意添加/删除任何方法)。
def legal(pos,dimensiones):
if pos[0] >= 0 and pos[0] < dimensiones[0] and pos[1] >= 0 and pos[1] < dimensiones[0]:
return True
else:
return False
class board:
def __init__(self,name,pieces,dimention,prohibited_positions):
self.name = name
self.pieces = pieces
self.dimention = dimention
self.prohibited_positions = prohibited_positions
self.free_positions = []
for x in range(dimention[0]):
for y in range(dimention[1]):
self.free_positions.append([x,y])
for x,y in self.prohibited_positions:
if [x,y] in self.free_positions:
self.free_positions.remove([x,y])
for piece in self.pieces:
if self.piece.position in self.free_positions:
self.free_positions.remove(piece.position)
def append(self,piece):
pos = piece.position
if pos in self.free_positions:
self.pieces.append(piece)
self.free_positions.remove(pos)
class piece:
def __init__(self,name,position,move_offsets):
self.name=name
self.position=position
self.move_offsets=move_offsets
self.possible_movements=move_offsets
def setPos(self,pos):
self.position=pos
def ValidMovements(self,dim,free_positions,prohibited_positions):
aux = []
for i in self.possible_movements:
newX = self.position[0] + i[0]
newY = self.position[1] + i[1]
newPos = [newX,newY]
if legal(newPos,dim):
aux.append(newPos)
for i in list(aux):
if i not in free_positions:
aux.remove(i)