|
发表于 2017-2-6 18:09:29
|
显示全部楼层
本帖最后由 Jonin616 于 2017-2-6 18:12 编辑
- def horsejump():
- dir_choise = [(-1,2),(-1,-2),(1,2),(1,-2),(-2,1),(-2,-1),(2,1),(2,-1)]
- dir_count = []
- for i in range(0,60):
- dir_count.append(0)
- bestway = []
- step = []
- count_step = 0
- horse_locate = [0,0]
- dest_locate = [7,7]
- step.append(horse_locate.copy())
- finish = 0
- back_flag = 0
- while finish == 0:
- while back_flag == 0:
- if horse_locate == dest_locate:
- break
-
- if count_step != 0 and dir_count[count_step] == 8:
-
- back_flag = 1
- break
- #print(step)
- if horse_locate != dest_locate and ((0 <= horse_locate[0] + dir_choise[dir_count[count_step]][0] <= 7) and (0 <= horse_locate[1] + dir_choise[dir_count[count_step]][1] <= 7)):
- if ([horse_locate[0] + dir_choise[dir_count[count_step]][0] ,horse_locate[1] + dir_choise[dir_count[count_step]][1]] in step):
- dir_count[count_step] += 1
- continue
- else:
- horse_locate[0] += dir_choise[dir_count[count_step]][0]
- horse_locate[1] += dir_choise[dir_count[count_step]][1]
- dir_count[count_step] += 1
- count_step += 1
- step.append(horse_locate.copy())
-
- if horse_locate != dest_locate and (horse_locate[0] + dir_choise[dir_count[count_step]][0] < 0 or horse_locate[0] + dir_choise[dir_count[count_step]][0] > 7 or horse_locate[1] + dir_choise[dir_count[count_step]][1] < 0 or horse_locate[1] + dir_choise[dir_count[count_step]][1] > 7):
- dir_count[count_step] += 1
- continue
- if back_flag == 1:
- dir_count[count_step] = 0
- count_step -= 1
- step.remove(horse_locate.copy())
- horse_locate = step[count_step].copy()
- back_flag = 0
-
- if horse_locate == dest_locate:
- back_flag = 1
- if len(bestway) == 0:
- for i in step:
- bestway.append(i.copy())
- if len(step) < len(bestway):
- #这里用print函数测试下输出结果
- print('输出目前的最优路径长度:',len(step))
- bestway.clear()
- for i in step:
- bestway.append(i.copy())
- if dir_count[0] == 8:
- finish = 1
- print(bestway)
-
复制代码 |
|