采用非递归暴力回溯方法,程序执行3分钟左右。
from Stack import Stack # j假设你以前自己定义好一个栈类
import datetime
'''
算法思路
1、指定一个当前点
2、根据“马”的走法确定马的前进位置(已经走过的位置除外)
3、如果当前位置全部失败,则返回离当前位置最近的点重新向前搜索
终止条件为64格子全部都走过
'''
def passable(next_loct,move_road):
i = next_loct[0]
j = next_loct[1]
# print ("当前经过的路线为{0}".format(move_road))
if i >= 0 and i <= 7 and j >= 0 and j <= 7 and (not (next_loct in move_road)):
# 如果下一步移动位置位于棋盘内且未经过,返回True
return True
return False
def horse_travel(start_grid):
# 马的移动方向
horse_dirc = [(-2,1), (-1,2), (1,2), (2,1), (2,-1), (1,-2), (-1,-2), (-2,-1)]
st = Stack()
# 初始化栈,栈中元素为列表,包含起点位置,下一搜索方向及一个用于标识该点为第一次使用的标志
st.push([start_grid,0])
move_road = [start_grid] # 用于维护行走路线
while not st.is_empty():
now_loct = st.pop() # 弹出下一个前进位置
next