简体   繁体   English

在矩阵中查找最大和路径的坐标

[英]Finding the coordinates of max sum path in matrix

I have this method which returns the max sum of the path from top left to bottom right (can move only to the right or bottom).我有这个方法,它返回从左上角到右下角的路径的最大总和(只能移动到右边或底部)。

def max_path(grid):
 
    N = len(grid)
    M = len(grid[0])
 
    sum = [[0 for i in range(M + 1)] for i in range(N + 1)]
 
    for i in range(1, N + 1):
        for j in range(1, M + 1):
 
            sum[i][j] = (max(sum[i - 1][j], sum[i][j - 1]) + grid[i - 1][j - 1])
            
    return sum[N][M]
 
 
matrix = [[1, 2, 3], [3, 4, 5]]
 
print(max_path(matrix))

output: 1 + 3 + 4 + 5 = 13 output:1 + 3 + 4 + 5 = 13

But what I want to get is also the coordinates of the points of the path: [(0,0) (1,0) (1,1) (1,2)]但我想得到的也是路径点的坐标: [(0,0) (1,0) (1,1) (1,2)]

You can try the below code to get your job done.您可以尝试以下代码来完成您的工作。

from itertools import permutations, product

def get_max_sum(table):
    height, width = len(table), len(table[0])

    sum_, *pos = max((sum(table[x][y] for x, y in zip(*pairs)), *zip(*pairs))
               for pairs in product(
                permutations(range(height)),
               ([*range(i, width), *range(i)] for i in range(width))))

    return (sum_, *sorted(pos))

sum_, *pos = get_max_sum(
    [[1, 2, 3],
     [2, 3, 5],
     [4, 9, 16]]
)

Output: 20 #maximum sum (0, 1) (1, 0) (2, 2) #co -ordinates Output: 20 #最大和 (0, 1) (1, 0) (2, 2) #坐标

The variable sum after the nested-for loops (as written in your code) is嵌套for循环之后的变量sum(如您的代码中所写)是

[0, 0, 0, 0],
[0, 1, 3, 6],
[0, 4, 8, 13]

You can work out the coordinates of the max sum by having a initial "pointer" at the bottom right corner (i=1, j =2, ignoring the zeros), and comparing the values that is on the top (i=0, i=2) and on the left (i=1, j=1).您可以通过在右下角设置一个初始“指针”(i=1,j =2,忽略零)并比较顶部的值(i=0, i=2) 和左侧 (i=1, j=1)。 Since 8 is larger than 6, we move the "pointer" to the left, and now i=1, j=1.由于 8 大于 6,我们将“指针”向左移动,现在 i=1,j=1。

4 is larger than 3, so we move the pointer to 4 (i=1, j=0) 4大于3,所以我们把指针移到4(i=1,j=0)

1 is larger than 0, so we move the pointer to 1 (i=0, j=0) 1大于0,所以我们把指针移到1(i=0, j=0)

A basic (untested) implementation of the algorithm is as follows:该算法的基本(未经测试)实现如下:

def max_path(grid):
 
    N = len(grid)
    M = len(grid[0])
 
    sum = [[0 for i in range(M + 1)] for i in range(N + 1)]
 
    for i in range(1, N + 1):
        for j in range(1, M + 1):
 
            sum[i][j] = (max(sum[i - 1][j], sum[i][j - 1]) + grid[i - 1][j - 1])

    j = M
    i = N
  
    path = []
    while i >  0 and j > 0:
      path.append((i-1,j-1))
      if sum[i-1][j] <= sum[i][j-1]:
        j -= 1 
      else:
        i -= 1
      
    path.reverse()
    return sum[N][M],path
matrix = [[1, 2, 3], [3, 4, 5]]
print(max_path(matrix))

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

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