Fancy DSA Fancy DSA
数据结构
算法
LeetCode
  • 关于
  • 导航 (opens new window)
  • 分类
  • 标签
  • 归档
设计模式 (opens new window)
博客 (opens new window)
GitHub (opens new window)

Jonsam NG

想的更多,也要想的更远
数据结构
算法
LeetCode
  • 关于
  • 导航 (opens new window)
  • 分类
  • 标签
  • 归档
设计模式 (opens new window)
博客 (opens new window)
GitHub (opens new window)
  • 开始上手
  • Plan 计划
  • Roadmap 路线
  • 算法简介
  • Sort 排序

  • Search 搜索

  • Recursive 递归

  • Graph 图

  • Tree 树

  • Math 数学

  • Hash 哈希

  • String 字符串

  • BitManipulation 位操纵

  • Backtracking 回溯

  • DynamicProgramming 动态规划

    • ClimbingStairs [爬楼梯]
    • CoinChange [钱币兑换]
    • EditDistance [编辑距离]
    • FibonacciNumber [斐波那契数]
    • FindMonthCalendar [月历]
    • KadaneAlgo [最大连续子数组和之Kadane算法]
    • LevenshteinDistance [莱文斯坦距离]
    • LongestCommonSubsequence [最长公共子序列]
    • LongestIncreasingSubsequence [最长递增子序列]
    • LongestPalindromicSubsequence [最长回文子序列]
    • LongestValidParentheses [最长合法括号]
    • MaxNonAdjacentSum [最大非连接子集和]
    • MaxProductOfThree [最大三数积]
    • MinimumCostPath [最小代价路径]
      • 介绍
      • 演示
      • 实现
    • NumberOfSubsetEqualToGivenSum [等和子集]
    • RodCutting [棒材切割问题]
    • Shuf [随机样本]
    • SieveOfEratosthenes [埃拉托斯特尼筛法]
    • SlidingWindow [滑窗]
    • SudokuSolver [数独]
    • TrappingRainWater [接住雨水]
    • TribonacciNumber [翠波那契数]
    • ZeroOneKnapsack [零一背包]
  • Cache 缓存

  • Array 数组

  • Ciphers 密码学

  • Conversions 转换

  • ProjectEuler 欧拉计划

  • 其他

  • 算法
  • DynamicProgramming 动态规划
jonsam
2022-09-26
目录

MinimumCostPath [最小代价路径]

# 介绍

给定一个二维矩阵,其中每一个元素代表通过该格子的代价,计算从左上角到右下角的最小代价及其路径。

# 演示

# 实现

# JavaScript

// Problem Statement => https://www.youtube.com/watch?v=lBRtnuxg-gU
/*
Find the min cost path from top-left to bottom-right in matrix
>>> minCostPath([[2, 1], [3, 1], [4, 2]])
>>> 6
*/
const minCostPath = (matrix) => {
  const n = matrix.length
  const m = matrix[0].length

  // moves[i][j] => minimum number of moves to reach cell i, j
  const moves = new Array(n)
  for (let i = 0; i < moves.length; i++) moves[i] = new Array(m)

  // base conditions
  moves[0][0] = matrix[0][0] // to reach cell (0, 0) from (0, 0) is of no moves
  for (let i = 1; i < m; i++) moves[0][i] = moves[0][i - 1] + matrix[0][i]
  for (let i = 1; i < n; i++) moves[i][0] = moves[i - 1][0] + matrix[i][0]

  for (let i = 1; i < n; i++) {
    for (let j = 1; j < m; j++) moves[i][j] = Math.min(moves[i - 1][j], moves[i][j - 1]) + matrix[i][j]
  }

  return moves[n - 1][m - 1]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
编辑 (opens new window)
上次更新: 2022/10/25, 20:46:09
MaxProductOfThree [最大三数积]
NumberOfSubsetEqualToGivenSum [等和子集]

← MaxProductOfThree [最大三数积] NumberOfSubsetEqualToGivenSum [等和子集]→

最近更新
01
0-20题解
10-31
02
本章导读
10-31
03
算法与转换:Part1
10-28
更多文章>
Theme by Vdoing | Copyright © 2022-2022 Fancy DSA | Made by Jonsam by ❤
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式