r,c=4,4defisSafe(maze,x,y):if x>=0and x<c and y>=0and y<r and maze[y][x]==1:returnTruereturnFalsedefsolvemaze(maze,x,y,sol):if x==c-1and y==r-1:
sol[y][x]=1returnTrueif isSafe(maze,x,y)==True:
sol[y][x]=1if solvemaze(maze,x,y+1,sol)==True:returnTrueif solvemaze(maze,x+1,y,sol)==True:returnTrue
sol[y][x]=0returnFalsedefsolve(maze):
sol=[[0for i inrange(c)]for i inrange(r)]# sol=[[0]*c]*r #用这个方式结果就出错if solvemaze(maze,0,0,sol)==False:#sol 是可变类型,传引用print("can not output path")returnFalse
printReslut(sol)return sol
defprintReslut(sol):for r in sol:for e in r:print(str(e)+" ",end=" ")print(" ")
maze =[[1,0,0,0],[1,1,0,1],[0,1,0,0],[1,1,1,1]]print("maze")
printReslut(maze)print("*********result********")
solve(maze)
result:
maze
1000110101001111*********result********1000110001000111*************************************
2、最小编辑距离,将str1转为str2需要几步操作
defeditDistance(str1,str2,m,n):if m==0:return n
if n==0:return m
if str1[m-1]==str2[n-1]:return editDistance(str1,str2,m-1,n-1)return1+min(editDistance(str1,str2,m-1,n-1),editDistance(str1,str2,m-1,n),editDistance(str1,str2,m,n-1))if __name__=="__main__":
str1="greek"
str2="greesak"print(editDistance(str1,str2,len(str1),len(str2)))
result :2 插入s,插入a
***************************************
1、回朔解决迷宫问题r,c=4,4def isSafe(maze,x,y): if x&amp;amp;gt;=0 and x&amp;amp;lt;c and y&amp;amp;gt;=0 and y&amp;amp;lt;r and maze[y][x]==1: return True return False def solvemaze(maze,x,y,sol): if x==c-1 and y==r-1.