forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimumCostPath.js
More file actions
Latest commit
45 lines (35 loc) · 1.05 KB
/
Copy pathMinimumCostPath.js
File metadata and controls
45 lines (35 loc) · 1.05 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Problem Statement => https://www.youtube.com/watch?v=lBRtnuxg-gU
constminCostPath=(matrix)=>{
/*
Find the min cost path from top-left to bottom-right in matrix
>>> minCostPath([[2, 1], [3, 1], [4, 2]])
>>> 6
*/
constn=matrix.length
constm=matrix[0].length
// moves[i][j] => minimum number of moves to reach cell i, j
constmoves=newArray(n)
for(leti=0;i<moves.length;i++)moves[i]=newArray(m)
// base conditions
moves[0][0]=matrix[0][0]// to reach cell (0, 0) from (0, 0) is of no moves
for(leti=1;i<m;i++)moves[0][i]=moves[0][i-1]+matrix[0][i]
for(leti=1;i<n;i++)moves[i][0]=moves[i-1][0]+matrix[i][0]
for(leti=1;i<n;i++){
for(letj=1;j<m;j++){
moves[i][j]=Math.min(moves[i-1][j],moves[i][j-1])+matrix[i][j]
}
}
returnmoves[n-1][m-1]
}
export{minCostPath}
// Example
// minCostPath([
// [2, 1],
// [3, 1],
// [4, 2]
// ])
// minCostPath([
// [2, 1, 4],
// [2, 1, 3],
// [3, 2, 1]
// ])