##棋盘长宽
X = 15
Y = 15
##相对与初始位置马可以选择走的步数
STEP = 8
##马可以选择走的方式
nextList = [(2, -1), (2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2)]
##出发点
startPoint=(0,0)
chess=[[0 for j in range(Y)] for i in range(X)]
print(chess)
##判断下一步是否可走
def nextOk(point, i):
nextp = (point[0] + nextList[i][0], point[1] + nextList[i][1])#获取偏移后坐标
if 0 <= nextp[0] < X and 0 <= nextp[1] < Y and chess[nextp[0]][nextp[1]] == 0:#判断落子是否在棋盘内,并且未被走过
return True, nextp
else:
return False, point
##获得下一步可走列表
def findNext(point):
list = []
for i in range(STEP):
ok, pointn = nextOk(point, i) #(2,0),0-7 把能走的坐标都放入列表中返回
if ok:
list.append(pointn)
return list
##获得步数最少的下一步(贪婪算法)
def getBestNext(point, step): #(2,0),2
# temp =X+1
temp =8
best = (-1, -1)
list = findNext(point)
lenp = len(list)
for i in range(lenp):
n = len(findNext(list[i]))#在第二步的基础上,找第三步坐标可能性的列表长度
if n < temp:
if n > 0:
temp = n
best = list[i] #挑步数最少的作为第二步坐标
elif n == 0 and step == X * Y:
best = list[i]
return best
##迭代方式 贪婪算法
def traverseFast(point, step): #(2,0),1
chess[point[0]][point[1]] = step #chess=[[0,0,0],[0,0,0],[1,0,0]
while 1:
step += 1
best = getBestNext(point, step)
if best[0] == -1:
return step
else:
chess[best[0]][best[1]] = step #把第二步坐标处改为2
point = best #起始坐标改为第二步坐标
def testFast():
step = traverseFast(startPoint, 1) #(2,0) 1
if step - 1 == X * Y:
print('快速遍历成功')
else:
print('快速遍历失败')
if __name__ == '__main__':
testFast()
'''
总结:
1.初始化棋盘:二维X*Y
2.八种相对初始坐标的偏移
3,初始位置的选定
4.找到指定第一步位置,将0改为1
5,用一个死循环,第二步判断哪些位置可走,获取偏移后坐标,判断落子是否在棋盘内,并且未被走过,8种方式,将其第二步坐标添加到列表之中,
再从第二步列表中坐标作为初始坐标,再走8种偏移获取第三步坐标列表,从中挑取列表长度最短的作为第二步坐标
6.如果列表长度为0说明,马的位置已经全部走完,可以比较其步数是否等于x*y,如果列表长度不为0可以继续迭代
'''