gpt4 book ai didi

java - 如何用矩阵中的最小和计算从 [0,0] 到 [M, N] 的路径?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:06:02 26 4
gpt4 key购买 nike

我需要计算从 [0,0] 到 [M, N] 的路径,矩阵中的最小和仅向右或向下移动?

我找到了这样的链接 https://www.programcreek.com/2014/05/leetcode-minimum-path-sum-java/但动态规划选项根本不清楚。

我试图用 BFS 算法自己实现它,但这是一个缓慢的解决方案

public int minPathSum(final int[][] grid) {
if (grid.length == 1 && grid[0].length == 1) {
return grid[0][0];
}
final int[][] moves = {new int[]{1, 0}, new int[]{0, 1}};
final Queue<int[]> positions = new ArrayDeque<>();
final Queue<Integer> sums = new ArrayDeque<>();
positions.add(new int[]{0, 0});
sums.add(grid[0][0]);
int minSum = Integer.MAX_VALUE;
while (!positions.isEmpty()) {
final int[] point = positions.poll();
final int sum = sums.poll();
for (final int[] move : moves) {
final int x = point[0] + move[0];
final int y = point[1] + move[1];
if (x == grid.length - 1 && y == grid[0].length - 1) {
minSum = Math.min(minSum, sum);
} else if (x > -1 && y > -1 && x < grid.length && y < grid[0].length) {
positions.add(new int[]{x, y});
sums.add(sum + grid[x][y]);
}
}
}
return minSum + grid[grid.length - 1][grid[0].length - 1];
}

您能否解释一下,如果可能的话请提供您将如何解决它?

最佳答案

我对如何实现广度优先搜索感到有点困惑,但很难理解这里的动态公式,这对我来说似乎更简单:)

这几乎是经典的动态规划问题。到达任何单元格时,solution[y][x],除了第一个,最多有两个前导:option 1option 2。假设我们知道达到每一个的最佳解决方案,我们会选择哪条边?显然这两个选项中更好!

稍微正式一点,如果 M 持有给定的值:

solution[0][0] = M[0][0]

// only one choice along
// the top horizontal and
// left vertical

solution[0][x] =
M[0][x] + solution[0][x - 1]

solution[y][0] =
M[y][0] + solution[y - 1][0]

// two choices otherwise:
// the best of option 1 or 2

solution[y][x] =
M[y][x] + min(
solution[y][x - 1],
solution[y - 1][x]
)

我们可以看到,我们可以创建一个适当的例程,例如使用 for 循环,以“自下而上”的顺序访问我们的 solution 矩阵的单元格,因为每个单元格的值取决于我们已经计算出的一个或两个前辈。

JavaScript 代码:

function show(M){
let str = '';
for (let row of M)
str += JSON.stringify(row) + '\n';
console.log(str);
}

function f(M){
console.log('Input:\n');
show(M);

let solution = new Array();
for (let i=0; i<M.length; i++)
solution.push(new Array(M[0].length).fill(Infinity));

solution[0][0] = M[0][0];

// only one choice along
// the top horizontal and
// left vertical

for (let x=1; x<M[0].length; x++)
solution[0][x] =
M[0][x] + solution[0][x - 1];

for (let y=1; y<M.length; y++)
solution[y][0] =
M[y][0] + solution[y - 1][0];

console.log('Solution borders:\n');
show(solution);

// two choices otherwise:
// the best of option 1 or 2

for (let y=1; y<M.length; y++)
for (let x=1; x<M[0].length; x++)
solution[y][x] =
M[y][x] + Math.min(
solution[y][x - 1],
solution[y - 1][x]
);

console.log('Full solution:\n');
show(solution);

return solution[M.length-1][M[0].length-1];
}

let arr = [];
arr[0] = [0, 7, -7];
arr[1] = [6, 7, -8];
arr[2] = [1, 2, 0];

console.log(f(arr));

关于java - 如何用矩阵中的最小和计算从 [0,0] 到 [M, N] 的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55192312/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com