Skip to content

Commit b391751

Browse files
committed
Added Minimum Cost Path Algorithm
1 parent af081a2 commit b391751

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// youtube Link -> https://www.youtube.com/watch?v=lBRtnuxg-gU
2+
3+
const minCostPath = (matrix) => {
4+
/*
5+
Find the min cost path from top-left to bottom-right in matrix
6+
>>> minCostPath([[2, 1], [3, 1], [4, 2]])
7+
6
8+
*/
9+
const n = matrix.length
10+
const m = matrix[0].length
11+
12+
// Preprocessing first row
13+
for (let i = 1; i < m; i++) {
14+
matrix[0][i] += matrix[0][i - 1]
15+
}
16+
17+
// Preprocessing first column
18+
for (let i = 1; i < n; i++) {
19+
matrix[i][0] += matrix[i - 1][0]
20+
}
21+
22+
// Updating cost to current position
23+
for (let i = 1; i < n; i++) {
24+
for (let j = 1; j < m; j++) {
25+
matrix[i][j] += Math.min(matrix[i - 1][j], matrix[i][j - 1])
26+
}
27+
}
28+
29+
return matrix[n - 1][m - 1]
30+
}
31+
32+
const main = () => {
33+
console.log(minCostPath([[2, 1], [3, 1], [4, 2]]))
34+
console.log(minCostPath([[2, 1, 4], [2, 1, 3], [3, 2, 1]]))
35+
}
36+
37+
main()

0 commit comments

Comments
 (0)