基于Switch与Rotate操作的大理石排序算法优化求助
问题:受限操作下的大理石排序算法困境
需要对一组「大理石」(从0开始的连续整数序列,每个数需归位到对应索引位置)进行排序,允许的操作仅有两种:
- switch:交换列表前两个元素
- rotate:将列表首个元素移至末尾(例如对(1,2,3)执行rotate后得到(2,3,1))
两种操作可任意次数、任意顺序执行。
我目前采用的思路是:若首个元素小于第二个,则执行switch将较大元素移至首位,随后执行rotate将其移至末尾,重复此逻辑直至序列有序。该方法仅对部分序列(如[1,3,0,2])有效,但对另一些序列(如[1,3,2,0,4])会陷入无限循环,始终重复某一序列无法推进。
我曾见过类似问题的提问,但现有回答仅涉及代码结构,未讲解核心算法。恳请提供算法层面的帮助!
class MarblesBoard: # 用给定的输入序列初始化棋盘(需为从0开始的连续整数序列,顺序任意) def __init__(self, sequence): self.positions = [] for marble in sequence: self.positions.append(marble) # 交换棋盘的前两个元素 def switch(self): self.positions[0], self.positions[1] = self.positions[1], self.positions[0] # 取出首个大理石并移至棋盘末尾 def rotate(self): self.positions.append(self.positions.pop(0)) # 创建str和repr输出字符串 def __str__(self): output = "" for marble in self.positions: output += (str(marble)+ " ") output = output.strip() return output def __repr__(self): output = "" for marble in self.positions: output += (str(marble)+ " ") output = output.strip() return output # 检查所有大理石是否处于正确位置(是否已解决) def is_solved(self): for i in range(len(self.positions)): if i != self.positions[i]: return False return True class Solver: # 用已创建的MarblesBoard对象和游戏历史初始化游戏 def __init__(self, board): self.board = board self.history = [("start", str(self.board))] # 解决游戏(当前算法为switch将前两元素中较大值移至首位,再rotate将其推至末尾) def solve(self): while not self.board.is_solved(): if self.board.positions[0] < self.board.positions[1]: self.board.switch() self.history.append(("switch", str(self.board))) self.board.rotate() self.history.append(("rotate", str(self.board))) return self.history # 使用提供的测试用例运行代码(该用例可正常运行) board = MarblesBoard([1,3,0,2]) solver = Solver(board) solver.solve()
内容的提问来源于stack exchange,提问作者AssimilateThis_
相关产品推荐
相关产品推荐

