【发布时间】:2016-03-14 00:23:39
【问题描述】:
我试图通过一个数组找到长度为 n 的每一个“步行”。在这种情况下,游走被定义为数组中相邻元素(水平、对角线或垂直)的长度为 n 的序列,以便重复该点。例如,一个 2x2 矩阵
[1 2]
[4 8]
会有长度为 2 的步行:(1, 2), (1, 4), (1, 8), (2, 1), (2, 4), (2, 8) ...
长度为 3 的路径:(1, 2, 4), (1, 2, 8), (1, 4, 2), (1, 4, 8) ... 等等
我如何在 python/numpy 中为小型 (5x5) 矩阵实现这种算法的快速实现,可能使用我目前不知道的数学的某些方面?
当前缓慢的实施:
from copy import deepcopy
def get_walks(arr, n):
n = n-1
dim_y = len(arr)
dim_x = len(arr[0])
# Begin with every possibly starting location
walks = [[(y, x)] for y in range(dim_y) for x in range(dim_x)]
# Every possible direction to go in
directions = [(0,1), (1,1), (1,0), (1, -1), (0, -1), (-1,-1), (-1, 0), (-1, 1)]
temp_walks = []
for i in range(n):
# Go through every single current walk and add every
# possible next move to it, making sure to not repeat any points
#
# Do this n times
for direction in directions:
for walk in walks:
y, x = walk[-1]
y, x = y+direction[0], x+direction[1]
if -1 < y < dim_y and -1 < x < dim_x and (y, x) not in walk:
temp_walks.append(walk + [(y, x)])
# Overwrite current main walks list with the temporary one and start anew
walks = deepcopy(temp_walks)
temp_walks = []
return walks
【问题讨论】:
-
您的步行是否需要支持最长 N 或无限的长度?
-
对于任何给定的 y x x 矩阵,最长可能的步行将是 (y*x),因此直到 n 为止都是有限的。
-
我的错,它是用python 3.5编写的,我会更新它。
-
你不能。有太多的步行。不管你如何生成它们,输出的绝对大小对于任何其他非常小的矩阵来说都太大了。
-
从角度来看,考虑一个
NxN数组。考虑从左上角到右下角的路径。仅考虑向右和向下移动,您有二项式 (2N N) 方式,这已经是指数级的了。添加可以上下或左右移动的步行...
标签: python arrays numpy optimization