Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a2b8643

Browse files
authored
Create minimum-cost-matrix.js
1 parent 6f42ef9 commit a2b8643

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

‎minimum-cost-matrix.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
const dynamicProgramming = () => {
2+
const DP = [];
3+
for (let i = 0; i < columns; i++) {
4+
DP[i] = [];
5+
}
6+
DP[0][0] = matrix[0][0];
7+
8+
for (let row = 1; row < rows; row++) {
9+
DP[row][0] = DP[row - 1][0] + matrix[row][0];
10+
}
11+
for (let col = 1; col < columns; col++) {
12+
DP[0][col] = DP[0][col - 1] + matrix[0][col];
13+
}
14+
15+
for (let row = 1; row < rows; row++) {
16+
for (let col = 1; col < columns; col++) {
17+
DP[row][col] =
18+
matrix[row][col] +
19+
Math.min(DP[row - 1][col - 1], DP[row - 1][col], DP[row][col - 1]);
20+
}
21+
}
22+
23+
console.log(DP[rows - 1][columns - 1]);
24+
};
25+
26+
const solution = (row, col) => {
27+
if (row < 0 || col < 0) {
28+
return Number.POSITIVE_INFINITY;
29+
} else if (row === 0 && col === 0) {
30+
return matrix[row][col];
31+
} else {
32+
const right = solution(row - 1, col - 1);
33+
const down = solution(row - 1, col);
34+
const diagnol = solution(row, col - 1);
35+
return matrix[row][col] + Math.min(right, down, diagnol);
36+
}
37+
};
38+
39+
const destX = 2;
40+
const destY = 2;
41+
const matrix = [[1, 2, 3], [4, 8, 2], [1, 5, 3]];
42+
const rows = matrix.length;
43+
const columns = matrix[0].length;
44+
console.log(dynamicProgramming());

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /