【问题标题】:Fastest way to find path from top left to bottom right of a matrix从矩阵的左上角到右下角找到路径的最快方法
【发布时间】:2020-11-13 23:16:45
【问题描述】:

假设我们有一个n x m 矩阵,其中的单元格要么是空的,要么是满的。左上角和右下角的单元格都是空的。您可以向上、向下、向左或向右移动。查看长度为<= T 的空单元格的路径是否连接左上角和右下角的最快方法是什么?我已经尝试了 DFS 和 BFS,并使用一个矩阵来跟踪到达特定单元格所花费的时间,但是这两种方法都太慢了。

编辑:我无法再访问代码,但这是我所做的伪代码。

def find_path(grid, T):
    visited = array(grid.dims)
    visited.fill(0)
    stack = []
    stack.append((0, 0, T))
    while len(queue) > 0:
        pos = stack.pop()
        if pos[0] == len(grid) and pos[1] == len(grid[0]):
            return True
        if pos[2] > 0:
            if pos[0] < len(grid)-1 and grid[pos[0]+1][pos[1]] == empty and visited[pos[0]+1][pos[1]] < T-1:
                visited[pos[0]+1][pos[1]] = T-1
                stack.append(pos[0]+1, pos[1], T-1)
            {same for right, left, up}
    return False

【问题讨论】:

  • 这两种方法都应该非常快。你一定在实现中做错了什么。哪个更快取决于矩阵的内容,但对于随机输入,DFS 平均会快一点,但 BFS 会找到最短路径。
  • 我就是这么想的!两者的实现都非常简单,我什至递归和迭代地实现了 DFS,但是在同一测试用例子集上超过了时间限制。
  • 如果您发布最简单的实现,这里的人们会很乐意向您展示它的缺陷所在。通常此类问题的 TLE 来自未能跟踪和避免以前访问过的单元格。
  • DFS 应该可以正常工作,在此处添加您的代码以便解决问题

标签: algorithm


【解决方案1】:

我不太确定您要对访问的数组做什么,但是“跟踪到达特定单元格所花费的时间”不适用于 DFS,并且对于 BFS 是不必要的.可能您的真实代码存在问题。

解决这个问题的直接方法是使用逐级 BFS,例如(在类似的伪代码中):

def hasPath(grid,T):
    gridcopy = copy(grid)
    level=[(0,0)]
    for pathlen in 1..T-1:
       # Invariant: the positions in level are at path length pathlen
       nextlevel=[]
       for (x,y) in level:
           # each valid direction is north plus maybe southwest and maybe southeast
           for sw in 0..1, se in 0..1:
               testx = x-sw+se
               testy = y-1+sw+se
               if testx >= 0 and 
                  testy >= 0 and 
                  testx < grid.width and 
                  testy < grid.height and
                  gridcopy[testy][testx] == empty:
                  
                  if testx==grid.width-1 and testy==grid.height-1
                       return True
                  nextlevel.append((testx,testy))
                  gridcopy[testy][testx] = blocked
       level = nextlevel
    return false   

【讨论】:

  • 为什么“跟踪到达特定单元所花费的时间”不适用于 DFS?在 DFS 中,对于无效路径,您可能会到达单元格 (x, y) 剩余 4 步,但在新路径上,如果剩余超过 4 步,您仍需要考虑单元格 (x, y)。
  • 因为使用 DFS,您可以在找到第一个单元格后找到到给定单元格的较短路径,这意味着您必须为该单元格编写较短的长度并从那里再次搜索 。使用 BFS,您总是首先找到最短路径,因此您不会遇到这个问题。
猜你喜欢
  • 1970-01-01
  • 2019-09-17
  • 1970-01-01
  • 2021-05-03
  • 1970-01-01
  • 2022-06-25
  • 2023-03-26
  • 1970-01-01
  • 2021-11-05
相关资源
最近更新 更多