我做出了下一个功能来解决大鼠迷宫的问题,其中大鼠只能向前和向下移动,我需要找到可能的方法数量。我做到了,但我想避免全局变量"可能的_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)
在这种情况下,您可以使函数返回值(对于其中的所有可能的代码路径 - 每当第一个if
条件不正确时,您的代码返回了None
(:
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)