从递归的矩阵中检索具有最低权重的路径

时间:2016-02-21 15:24:52

标签: java algorithm recursion matrix

假设我有一个 n ^ n 矩阵。在每个单元格中都有一个正数,我需要检索权重最低的路径

路径是从matrix[0][0]开始并以matrix[matrix.length-1][matrix[0].length-1]结尾,没有对角线的每条路径。

路径的

权重是其单元格中所有数字的数量。

例如,假设我有这个矩阵:

mat = {{1,2},{3,4}};

所以{1,2,4}路径{1,3,4}是另一个路径

第一条路径的重量 7 (1 + 2 + 4),第二条路径的重量 8 (1 + 3 + 4),所以该函数将返回 7

我需要递归地解决它。伪代码应该是这样的:

if i > matrix.length-1 || i < 0 || j > matrix[0].length-1 || j < 0
//then I passed the borders, so I need to step back.
if i == matrix.length-1 && j == matrix[0].length-1
//Then I reached the last cell, and I need to retrieve sum

然后调用四个递归调用:

public static int smallPath(a, i+1, j, sum);
public static int smallPath(a, i, j+1, sum);
public static int smallPath(a, i-1, j, sum);
public static int smallPath(a, i, j-1, sum);

然后我需要检索一些东西,什么?

我知道这不是最新的,但这是一般的想法,有人可以帮助我解决这个问题吗?谢谢!

1 个答案:

答案 0 :(得分:0)

你应该能够使用Dijstra的算法,其中节点是&#34;在&#34;之间。矩阵的细胞和连接由细胞的权重暗示。

如需详细解答,请参阅此问题:Javascript: Pathfinding in a (50000*50000 grid) 2d array?

相关问题