Python 在网格中导航
我在欧拉计划中偶然发现了一个问题,Python 在网格中导航,python,algorithm,navigation,grid,Python,Algorithm,Navigation,Grid,我在欧拉计划中偶然发现了一个问题, . 我用组合数学解决了这个问题,但我想知道这个问题或这类问题是否有一个动态规划的解决方案。比如说网格的一些方块被去掉了,这可以导航吗?我正在使用Python。我该怎么做?任何提示都将不胜感激。提前感谢。您可以做一个简单的回溯,并探索这样一个隐式图:(注释解释了其中的大部分) 最直接的方法是使用python内置的memonization util。您可以将缺失的正方形编码为缺失网格点(对)的冻结集(散列): 还有一个数学解决方案(可能就是您使用的): 这是因为路
. 我用组合数学解决了这个问题,但我想知道这个问题或这类问题是否有一个动态规划的解决方案。比如说网格的一些方块被去掉了,这可以导航吗?我正在使用Python。我该怎么做?任何提示都将不胜感激。提前感谢。您可以做一个简单的回溯,并探索这样一个隐式图:(注释解释了其中的大部分)
最直接的方法是使用python内置的memonization util。您可以将缺失的正方形编码为缺失网格点(对)的
冻结集
(散列):
还有一个数学解决方案(可能就是您使用的): 这是因为路径的数量与在
w+h
步骤上选择向右或向下移动的方式的数量相同,其中您向右移动w次,这等于w+h选择w
,或(w+h)!/(w!*h!)
对于缺少的方格,我认为有一个组合解决方案,但是如果有很多缺少的方格,那么速度会非常慢,所以动态规划可能会更好
例如,以下各项应起作用:
缺失=[
[0, 1],
[0, 0],
[0, 0],
]
定义路径辅助对象(x、y、路径网格,缺少):
如果路径网格[x][y]不是无:
返回路径网格[x][y]
如果缺少[x][y]:
路径网格[x][y]=0
返回0
elif x<0或y<0:
返回0
其他:
路径\计数=(路径\辅助对象(x-1,y,路径\网格,缺失)+
路径\辅助对象(x,y-1,路径\网格,缺失))
路径网格[x][y]=路径计数
返回路径计数
def路径(缺少):
arr=[[None]*w表示范围内(h)]
w=len(缺少[0])
h=透镜(缺失)
返回路径(w、h、arr、缺失)
打印路径()
如果您查看他们的论坛,您可以找到一些有趣的解决Project Euler问题的方法。例如,对于这一个,在页面的一半,有一个使用动态编程的Ruby解决方案。因此,这至少证实了在Python中也可以这样做。谢谢。问题只剩下如何消除丢失的方块,但感谢缓存提示!我一定会记住这一点。我想你已经有了它:D.你提到的解决方案确实和我使用的相同;现在剩下的就是消去了。@Kurns我的答案被编辑成包括消去。
def explore(r, c, n, memo):
"""
explore right and down from position (r,c)
report a rout once position (n,n) is reached
memo is a matrix which saves how many routes exists from each position to (n,n)
"""
if r == n and c == n:
# one path has been found
return 1
elif r > n or c > n:
# crossing the border, go back
return 0
if memo[r][c] is not None:
return memo[r][c]
a= explore(r+1, c, n, memo) #move down
b= explore(r, c+1, n, memo) #move right
# return total paths found from this (r,c) position
memo[r][c]= a + b
return a+b
if __name__ == '__main__':
n= 20
memo = [[None] * (n+1) for _ in range(n+1)]
paths = explore(0, 0, n, memo)
print(paths)
from functools import lru_cache
@lru_cache(None)
def paths(m, n, missing=None):
missing = missing or frozenset()
if (m, n) in missing:
return 0
if (m, n) == (0, 0):
return 1
over = paths(m, n-1, missing=missing) if n else 0
down = paths(m-1, n, missing=missing) if m else 0
return over + down
>>> paths(2, 2)
6
# middle grid point missing: only two paths
>>> paths(2, 2, frozenset([(1, 1)]))
2
>>> paths(20, 20)
137846528820
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
def paths(w, h):
return factorial(w + h) / (factorial(w) * factorial(h))
missing = [
[0, 1],
[0, 0],
[0, 0],
]
def paths_helper(x, y, path_grid, missing):
if path_grid[x][y] is not None:
return path_grid[x][y]
if missing[x][y]:
path_grid[x][y] = 0
return 0
elif x < 0 or y < 0:
return 0
else:
path_count = (paths_helper(x - 1, y, path_grid, missing) +
paths_helper(x, y - 1, path_grid, missing))
path_grid[x][y] = path_count
return path_count
def paths(missing):
arr = [[None] * w for _ in range(h)]
w = len(missing[0])
h = len(missing)
return paths_helper(w, h, arr, missing)
print paths()