|
发表于 2018-4-11 22:26:30
|
显示全部楼层
- # ! /urs/bin/env python
- # coding=utf-8
- # __author__ = 'bang' CreateDate:2018/4/11
- def findpath(startpoint, aimpoint):
- global stepcount
- global anserlist
- global FLAG
- FLAG += 1
- horsePos = startpoint # 记录起始位置
- for i in stepTrace:
- if horsePos == i[-1]:
- stepcount = len(i) - 1
- break
- if stepcount > min(minsteplist) - 1:
- FLAG -= 1
- return
- for history in historyPos[:]:
- if horsePos == history[0]:
- if stepcount > history[1]:
- FLAG -= 1
- return # 如果该点已经出现在历史记录的点中,且步数较高,则结束
- else:
- historyPos.append((horsePos, stepcount))
- historyPos.remove(history)
- break # 刷新某个点的最优步数记录
- else:
- historyPos.append((horsePos, stepcount)) # 位置加入历史记录
- horseNextPos = [(horsePos[0] + rule[0], horsePos[1] + rule[1]) for rule in HORSERULE
- if (horsePos[0] + rule[0], horsePos[1] + rule[1]) in CHESSBOARD] # 生成下个一可能的点
- if aimpoint in horseNextPos: # 如果目标点在下一个可能的点,则记录路径长度和路径结果
- for i in stepTrace:
- if i[-1] == horsePos and i not in anserlist:
- anserlist.append(i)
- minsteplist.append(len(i))
- # break
- FLAG -= 1
- return
- else:
- # 记录轨迹
- for i in stepTrace[:]:
- temp = i[:]
- if horsePos == temp[-1]:
- for point in horseNextPos:
- temp.append(point)
- stepTrace.append(temp[:])
- temp.pop()
- stepTrace.remove(temp)
- break
- for point in horseNextPos:
- findpath(point, aimpoint) # 遍历每个可能的点
- FLAG -= 1
- if FLAG == 0: # 返回到最外层的函数才打印结果
- for i in anserlist: # 输出达到终点的最短路径
- if len(i) == min(minsteplist):
- # i.append(aimpoint)
- print(i)
- print(minsteplist)
- print(len(historyPos))
- CHESSBOARD = tuple((i, j) for i in range(9) for j in range(10)) # 初始化象棋盘
- HORSERULE = tuple((i, j) for i in (-1, 1, 2, -2) for j in (-1, 1, 2, -2) if abs(i) + abs(j) == 3) # 定义马的行棋规则
- startPos = (0, 0) # input("请输入马的初始位置(以英文逗号隔开):")
- historyPos = [(startPos, 0)] # 记录马曾经经过的点,以及经过该点的步数
- aimPos = (7, 7) # input("请输入马的终点位置(以英文逗号隔开):")
- stepTrace = [[startPos]] # 记录每次行走的路径
- stepcount = 0 # 记录当前步数
- # 判断最小步数,默认1000以内肯定能找到解
- minsteplist = [1000]
- anserlist = []
- FLAG = 0
- findpath(startPos, aimPos)
复制代码
写了个贼蠢的,貌似是先深度优先的递归,调来调去搞不明白了,总有差错,先发上来。
后来再开车的时候,想到一个开枝散叶的广度优先法,应该会改进和简洁不少。一会实现一下发出来。
等发完后,再学习各位大神的方法 |
|