【问题标题】:Find longest path in matrix with adjacent letters在矩阵中找到具有相邻字母的最长路径
【发布时间】:2018-12-03 23:32:03
【问题描述】:

我正在尝试编写一个程序,该程序将显示给定任意大小矩阵的最长路径,该矩阵从一个字母移动到另一个字母,但只能移动到相邻的字母。

例如。如果你的字母是'E',你可以移动到'D'或'F'。您可以上下左右移动,但只能移动一个位置。现在我用数字做了一个类似的问题,你必须找到从左上角到右下角的路径,我假设这将是一个具有更多约束的类似问题。这就是我所拥有的,我不确定如何修改它以解决我需要为这个问题做的事情(有障碍,它只能通过 0):

def pathwithproblems(A):
    paths = [[0]*len(A[0] for i in A]
    if A[0][0] == 0:
        paths[0][0]=1
    for i in range(1, len(A)):
        if A[i][0] == 0:
            paths[i][0]=paths[i-1][0]
    for j in range(1, len(A)):
        if A[0][j] == 0:
            paths[0][j]=paths[0][j-1]
    for i in range(1, len(A)):
        for j in range(1, len(A)):
            if A[i][j] == 0:
                paths[i][j]=paths[i-1][j] + paths[i][j-1]
    return paths[-1][-1]

对于我的字母问题,例如,如果矩阵是:

L K M N O P Q R J
A B C D E F G H I

我的答案应该是:

JIHGFEDCBA

如果存在平局,我想返回具有最低行和列索引的那个,如果仍然存在平局,则返回任何一个都可以。任何帮助将不胜感激!

【问题讨论】:

    标签: python python-3.x matrix data-structures dynamic-programming


    【解决方案1】:
    Another way to solve this problem is to have a helper function which will calculate all the lengths of the paths having adjacent letters and then the calling function can store only the longest one.
    

    伪代码:

    helper(int[] mat, i, j, char c)
    {
    if i or j are outside the boundary conditions, return 0.
    if difference between mat[i][j] and c is 1:
        return Math.max(
            helper(mat, i+1,j,mat[i][j]),
            helper(mat, i-1,j,mat[i][j]),
            helper(mat, i,j+1,mat[i][j]),
            helper(mat, i,j-1,mat[i][j]))+1;
    else return 0;}
    

    【讨论】:

      【解决方案2】:

      这相当于一些图表。所以第一步是对图形进行 demine

      ABE
      DCZ
      

      会变成

      A-B E
        |
      D-C Z
      

      您现在可以在哪里搜索最长的路径(一些解决方案应该在互联网上)

      【讨论】:

      • 谢谢你,但我无法在网上找到任何类似的实现来转换为图形然后找到最长的路径。
      • 我想您需要手动将其转换为正确的图形。解决此问题的一种简单方法如下:然后您可以从任意顶点开始并计算到任何其他顶点的距离。
      猜你喜欢
      • 1970-01-01
      • 2019-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多