我下一个功能是解决老鼠迷宫的问题,在老鼠迷宫中,老鼠只能向前和向下移动,我需要找到许多可能的方法。我做到了,但我想避免使用全局变量“ possible_ways”。有什么方法可以改善我的代码?
possible_ways = 0
def solve(n,x,y):
if x == n-1 and y == n-1:
global possible_ways
possible_ways = possible_ways+1
return True
if x<=n-1 and y<=n-1:
solve(n,x+1,y)
solve(n,x,y+1)
solve(4,0,0)
print(possible_ways)
答案 0 :(得分:0)
在这种情况下,您可以使函数返回一个值(对于其中所有可能的代码路径-每当第一个None
条件不成立时,您的代码就返回if
):
def solve(n,x,y):
if x == n-1 and y == n-1:
return 1
if x <= n-1 and y <= n-1:
return solve(n,x+1,y) + solve(n,x,y+1)
return 0
possible_ways = solve(4,0,0)
print(possible_ways)