您的位置:首页 > 编程语言 > Python开发

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 象棋 棋盘