- 帖子
- 10
- 精华
- 0
- 积分
- 38
- 阅读权限
- 10
- 注册时间
- 2015-9-7
- 最后登录
- 2018-4-18
|
晚上对上面代码中不完善的地方做了进一步修正,修正如下:- def check(x1,y1,x2,y2): #检查是否到达指定的点
- if x1==x2 and y1==y2:
- return True
- return False
- def find_way(x1,y1,x2,y2):
- '''由于假设是从左下角开始走,所以我只用了马的四种走法(实际有八种),
- 我假设马只能向右侧走(因为要去右上角),并且优先采用了(1,2)和(2,1)这种走法'''
- global step
- if check(x1+1,y1+2,x2,y2):
- step+=1
- chessboard[x1][y1]=step
- step+=1
- chessboard[x1+1][y1+2]=step
- return step
- elif x1+1<x2 and y1+2<y2:
- step+=1
- chessboard[x1][y1]=step
- return find_way(x1+1,y1+2,x2,y2)
- if check(x1+2,y1+1,x2,y2):
- step+=1
- chessboard[x1][y1]=step
- step+=1
- chessboard[x1+2][y1+1]=step
- return step
- elif x1+2<x2 and y1+1<y2:
- step+=1
- chessboard[x1][y1]=step
- return find_way(x1+2,y1+1,x2,y2)
- if check(x1+2,y1-1,x2,y2):
- step+=1
- chessboard[x1][y1]=step
- step+=1
- chessboard[x1+2][y1-1]=step
- return step
- elif x1+2<x2 and y1-1<y2:
- step+=1
- chessboard[x1][y1]=step
- return find_way(x1+2,y1-1,x2,y2)
- if check(x1+1,y1-2,x2,y2):
- step+=1
- chessboard[x1][y1]=step
- step+=1
- chessboard[x1+1][y1-2]=step
- return step
- elif x1+1<x2 and y1-2<y2:
- step+=1
- chessboard[x1][y1]=step
- return find_way(x1+1,y1-2,x2,y2)
- #另外四种走法:
- if check(x1-2, y1+1, x2, y2):
- step += 1
- chessboard[x1][y1] = step
- return step
- elif 0 < x1-2 < x2 and y1+1 < y2:
- step += 1
- chessboard[x1][y1] = step
- return find_way(x1-2, y1+1, x2, y2)
- if check(x1-1, y1+2, x2, y2):
- step += 1
- chessboard[x1][y1] = step
- return step
- elif 0 < x1-1 < x2 and y1+2 < y2:
- step += 1
- chessboard[x1][y1] = step
- return find_way(x1-1, y1+2, x2, y2)
- if check(x1-1,y1-2,x2,y2):
- step+=1
- chessboard[x1][y1]=step
- return step
- elif 0 < x1-1 < x2 and 0< y1-2 < y2:
- step+=1
- chessboard[x1][y1]=step
- return find_way(x1-1,y1-2,x2,y2)
- if check(x1-2, y1-1, x2, y2):
- step += 1
- chessboard[x1][y1]=step
- return step
- elif 0 < x1-2 < x2 and 0 < y1-1 < y2:
- step += 1
- chessboard[x1][y1] = step
- return find_way(x1-2, y1-1, x2, y2)
- return -1
- cols=9
- rows=9
- chessboard = [[0 for col in range(cols)]for row in range(rows) ]
- step=0
- print(find_way(0,0,8,8)-1)
- chessboard.reverse()
- for i in range(cols):
- for j in range(rows):
- print (chessboard[i][j],'',end='',)
- print('\t')
复制代码 修正后的代码比之前稍微好些了,只是有时会存在递归太深的问题,暂时没想到具体原因 |
|