【问题标题】:Find the nearest idetical value in terms of distance in 2d list or array? [closed]在二维列表或数组中找到最接近的相同值? [关闭]
【发布时间】:2020-04-18 18:25:55
【问题描述】:

关于如何制作一个找到与起点值相同的最接近值的函数的任何想法。

例如,如果您有此列表,并且想要找到最接近左上角的1(也是一个)。

[[1, 0, 0, 0, 0, 1],
 [0, 0, 0, 0, 1, 0],
 [1, 0, 1, 0, 0, 0]]

最近的1 会在左下角,然后是底部中间一点点的左边(你不能走对角线,这样一个比左下角更远) .中间层和顶层的距离左上角起点的距离相等。

我的第一个想法是在列表中搜索第一个出现的,并通过仅在受限区域中搜索来限制搜索边界。因此,如果您有一个 10 x 10 的列表,然后在 [0, 5] 处找到第一个列表,则可以将搜索限制为 list[:6][:6],因此您只搜索 5 x 5 的列表。或者,如果您在 [3, 0] 处找到 1,则搜索可能仅限于 list[:4][:4]

但我认为这不是最有效的方法,所以我想知道是否其他人有一些想法或者可以将我推荐给一个可以很好地解释这一点的链接。

【问题讨论】:

    标签: python python-3.x function search multidimensional-array


    【解决方案1】:

    这是一个常见的问题:搜索最短路径。为此,您应该使用广度优先搜索。

    这是一个可能的实现:

    def closest(m, x, y): # x, y is starting point
        height = len(m)
        width = len(m[0])
        frontier = [(x,y)]
        visited = set()
        while len(frontier):
            newfrontier = []
            for cell in frontier:
                if cell not in visited:
                    visited.add(cell)
                    x, y = cell
                    for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):
                        newx = x + dx
                        newy = y + dy
                        neighbor = (newx, newy)
                        if newx >= 0 and newx < width and newy >= 0 and newy < height and neighbor not in visited:
                            if m[newy][newx] == 1: # bingo!
                                return neighbor
                            newfrontier.append(neighbor)
            frontier = newfrontier
    
    m = [[1, 0, 0, 0, 0, 1],
         [0, 0, 0, 0, 1, 0],
         [1, 0, 1, 0, 0, 0]]
    
    print(closest(m, 0, 0)) # ----> (0, 2)
    

    坐标为 (x, y),因此先列,然后是行。

    【讨论】:

    • 谢谢您,您的代码制作精良,变量非常清晰,因此我很容易理解,我非常感谢。再次感谢
    猜你喜欢
    • 2015-03-16
    • 2019-01-16
    • 1970-01-01
    • 2016-04-17
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多