Python学习笔记02----M*N的棋盘,马从坐下到右上的行走方式
2018-03-08 10:40
609 查看
题目:
下过象棋的人都知道,马只能走'日'字形(包括旋转90°的日),现在想象一下,给你一个n行m列网格棋盘,棋盘的左下角有一匹马,请你计算至少需要几步可以将它移动到棋盘的右上角,若无法走到,则输出-1.如n=1,m=2,则至少需要1步;若n=1,m=3,则输出-1。
#寻找下一步左右可能的点 def goNextStep(currentP,n,m): result=[] x=currentP[0] y=currentP[1] #分析理论8种情况 if x+1<=n and y+2<=m: result.append([x+1,y+2]) if x+1<=n and y-2>=0: result.append([x+1,y-2]) if x+2<=n and y-1>=0: result.append([x+2,y-1]) if x+2<=n and y+1<=m: result.append([x+2,y+1]) if x-1>=0 and y+2<=m: result.append([x-1,y+2]) if x-1>=0 and y-2>=0: result.append([x-1,y-2]) if x-2>=0 and y-1>=0: result.append([x-2,y-1]) if x-2>=0 and y+1<=m: result.append([x-2,y+1]) return result #获取下一步之后所有的路径点 def getAllPath(n,m,pathArr): allPathArrNew=[] for path in pathArr: nextWay1=goNextStep(path[len(path)-1],n,m) for point in nextWay1: #不走回头路 if path.count(point)==0: newPath=list(path) newPath.append(point) allPathArrNew.append(newPath) return allPathArrNew #找出所有最短路径 若没有则返回最终无法行走的路径 def findShortestPath(n,m): #第一步 stepFinal=[[[0,0]]] #最佳路径数组 bestPath=[] while True: stepNext=getAllPath(n,m,stepFinal) #无路可走则跳出 if(len(stepNext)==0) : break #记录此步 stepFinal=stepNext #某一条路到终点则记录 for path in stepNext: lastPoint=path[len(path)-1] if lastPoint[0]==n and lastPoint[1]==m: bestPath.append(path) #存在到达终点的路径则跳出 if len(bestPath)>0: break return bestPath if len(bestPath)!=0 else stepFinal #找出最短路径的步数 若无法到达则返回-1 def findShortestPathStepCount(n,m): #第一步 stepFinal=[[[0,0]]] #最佳路径数组 bestPath=[] while True: stepNext=getAllPath(n,m,stepFinal) #无路可走则跳出 if(len(stepNext)==0) : break #记录此步 stepFinal=stepNext #某一条路到终点则记录 for path in stepNext: lastPoint=path[len(path)-1] if lastPoint[0]==n and lastPoint[1]==m: bestPath.append(path) #存在到达终点的路径则跳出 if len(bestPath)>0: break return len(bestPath[0])-1 if len(bestPath)!=0 else -1
相关文章推荐
- python核心编程学习笔记-2016-07-20-02-整型对象缓存
- python数据结构学习笔记-2016-11-02-02-迷宫问题
- Python学习笔记:字符串格式化方式
- python数据结构学习笔记-2016-10-24-02-使用排序列表实现集合ADT
- JavaScript学习笔记-02对象创建方式
- iOS学习笔记02——以编码的方式实现Auto Layout自动布局(一)
- Python学习笔记- 廖雪峰教程【python 2】//为继续学习爬虫准备-02 [待完善]
- 深度学习(DL)与卷积神经网络(CNN)学习笔记随笔-02-基于Python的卷积运算
- python标准库学习笔记02-time,datetime包
- python数据结构学习笔记-2016-11-12-02-递归的应用
- Python的面向对象编程方式学习笔记
- Python学习笔记02-列表与操作列表
- Python学习笔记-02-循环测试条件中易犯错的要点及配套解决方案
- 02-python学习笔记:字典dict和集合set
- 编程小白的第一本 python 入门书 学习笔记02 第三章 变量与字符串
- python学习笔记(django入门02)
- Python学习笔记_02:使用Tkinter连接MySQL数据库实现登陆注册功能
- [Python][Scikit-learn][学习笔记02]逻辑回归之鸢尾花分类预测
- python 学习笔记(02)
- python数据结构学习笔记-2016-10-14-02-python列表