输出一系列操作使得魔方从当前状态调整为目标状态输出指令前先输出本次需要多少个指令格式为一个整数操作指令有12条对应与每个面的顺时针旋转和逆时针旋转每次操作旋转90度指令为二运组:视图名称旋转方向视图名称为:front back left right top bottom;旋转方向是:clockwise anticlockwise。例如:top clockwise举例:指定方块已经在复原位置直接输出
定义魔方初始状态和目标状态
start = "WWWBBBBBBGGGGGGYYYGGGWWWWWWBBBYYYYYYOOOOOOOOORRRRRRRRR" target = "WWWWWWWWWBBBBBBGGGGGGYYYRRRRRRRRROOOOOOOOOGGGGGGYYYYYBBB"
定义每个面的颜色索引
front = [0, 1, 2, 9, 10, 11, 18, 19, 20] back = [6, 7, 8, 15, 16, 17, 24, 25, 26] left = [0, 3, 6, 9, 12, 15, 18, 21, 24] right = [2, 5, 8, 11, 14, 17, 20, 23, 26] top = [0, 1, 2, 3, 4, 5, 6, 7, 8] bottom = [18, 19, 20, 21, 22, 23, 24, 25, 26]
定义旋转函数
def rotate(face, direction): # 根据旋转方向生成旋转后的面 if direction == "clockwise": new_face = [face[i] for i in [6, 3, 0, 7, 4, 1, 8, 5, 2]] else: new_face = [face[i] for i in [2, 5, 8, 1, 4, 7, 0, 3, 6]] return new_face
计算从初始状态到目标状态需要的步数和操作指令
steps = 0 instructions = [] for i in range(6): # 获取当前面的颜色索引和目标面的颜色索引 start_face = eval(['front', 'back', 'left', 'right', 'top', 'bottom'][i]) target_face = eval(target[i9:i9+9]) # 如果当前面不是目标面,进行旋转操作 if start_face != target_face: # 选择旋转方向 if start_face[0] == target_face[2] and target_face[0] == start_face[2]: direction = "anticlockwise" else: direction = "clockwise" # 执行旋转操作 start_face = rotate(start_face, direction) eval(['front', 'back', 'left', 'right', 'top', 'bottom'][i]) = start_face # 记录操作指令 instructions.append([['front', 'back', 'left', 'right', 'top', 'bottom'][i], direction]) steps += 1
输出结果
print(steps) for instruction in instructions: print(instruction[0], instruction[1]
原文地址: https://www.cveoy.top/t/topic/fFUl 著作权归作者所有。请勿转载和采集!