简体   繁体   English

使用 Python 在网格中严格增加路径

[英]Strictly Increasing Path in Grid with Python

At each step we can go the one of the left,right,up or down cells only if the that cell is strictly greater thab our current cell.在每一步,我们可以 go 只有当那个单元格严格大于我们当前的单元格时,我们才能 go 左,右,上或下单元格之一。 (We cannot move diagonally). (我们不能沿对角线移动)。 We want to find all the paths that we can go from the top-left cell to the bottom-right cell.我们想要找到从左上角单元格到右下角单元格的所有路径 go。

[[1,4,3], [5,6,7]] [[1,4,3], [5,6,7]]

In our example, these paths are 1->4->6->7 and 1->5->6->7.在我们的示例中,这些路径是 1->4->6->7 和 1->5->6->7。

How can i solve it in reversible use?我怎样才能在可逆使用中解决它?

First, note that the number of such paths is exponential (in the size of the graph).首先,请注意此类路径的数量是指数级的(在图形的大小中)。

For example, look at the graph:例如,看图:

1    2     3   ... n
2    3     4   ... n+1
3    4     5   ... n+2
...
n  (n+1) (n+2) ... 2n

In here, you have exactly n rights and n down - which gives you exponential number of such choices - what makes "efficient" solution irrelevant (as you stated, you are looking for all paths).在这里,你有n权利和n向下 - 这给你指数数量的这样的选择 - 是什么使得“有效”解决方案无关紧要(正如你所说,你正在寻找所有路径)。

One approach to find all solutions, is using a variation of DFS , where you can go to a neighbor cell if and only if it's strictly higher.找到所有解决方案的一种方法是使用DFS的变体,当且仅当它严格更高时,您可以 go 到相邻单元格。

It should look something like:它应该看起来像:

def Neighbors(grid, current_location):
  """returns a list of up to 4 tuples neighbors to current location"""
  pass  # Implement it, should be straight forward

# Note: Using a list as default value is problematic, don't do it in actual code.
def PrintPaths(grid, current_path = [(0,0)], current_location = (0, 0)):
  """Will print all paths with strictly increasing values.
  """
  # Stop clause: if got to the end - print current path.
  if current_location[0] == len(grid) and current_location[1] == len(grid[current_location[0]):
    print(current_path)
    return
  # Iterate over all valid neighbors:
  for next in Neighbors(grid, current_location):
    if grid[current_location[0]][current_location[1]] < grid[next[0]][next[1]]:
    current_path = current_path + next
    PrintPaths(grid, current_path, next)
    # When getting back here, all that goes through prefix + next are printed.
    # Get next out of the current path
    current_path.pop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM