骑士周游问题(非递归暴力回溯)

采用非递归暴力回溯方法,程序执行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
骑士周游问题是一个著名的 NP 问题,它的解决需要用到回溯算法。下面是骑士周游问题非递归实现: 1. 构建棋盘,初始化为 0 2. 记录下当前位置,从 (0, 0) 开始 3. 将当前位置的值设为步数 4. 如果当前步数等于棋盘大小,则成功退出 5. 如果当前步数小于棋盘大小,则按照预设的移动方向依次进行移动(注意判断是否越界),直到找到一个可行的位置 6. 如果找到了一个可行的位置,则继续执行步骤 3,否则回溯到上一个位置,修改当前位置的值为 0,继续寻找下一个可行位置 具体实现可以参考以下代码: ```python def knightTour(n): # 初始化棋盘 board = [[0] * n for i in range(n)] # 移动方向 moves = ((2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1)) # 记录当前位置 row, col = 0, 0 pos = 0 board[row][col] = pos while pos < n * n - 1: # 标记当前位置已被访问 board[row][col] = pos found = False # 尝试向下一个位置移动 for move in moves: next_row = row + move[0] next_col = col + move[1] if 0 <= next_row < n and 0 <= next_col < n and board[next_row][next_col] == 0: row, col = next_row, next_col pos += 1 found = True break # 如果无法找到下一个位置,回溯到上一个位置 if not found: board[row][col] = 0 pos -= 1 row, col = [i for i, row in enumerate(board) if pos in row][0], [row.index(pos) for row in board if pos in row][0] # 输出结果 for row in board: print(row) ``` 注意,这种非递归实现方式可能会比递归实现方式更复杂一些。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值