function maxCoins(board) {
const rows = board.length;
const cols = board[0].length;
const dp = Array.from({ length: rows }, () => Array(cols).fill(0));
dp[0][0] = board[0][0];
for (let i = 1; i < rows; i++) {
dp[i][0] = dp[i - 1][0] + board[i][0];
}
for (let j = 1; j < cols; j++) {
dp[0][j] = dp[0][j - 1] + board[0][j];
}
for (let i = 1; i < rows; i++) {
for (let j = 1; j < cols; j++) {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]) + board[i][j];
}
}
const path = [];
let row = rows - 1;
let col = cols - 1;
while (row >= 0 && col >= 0) {
path.push([row, col]);
if (row === 0) {
col--;
} else if (col === 0) {
row--;
} else {
if (dp[row - 1][col] > dp[row][col - 1]) {
row--;
} else {
col--;
}
}
}
return {
maxCoins: dp[rows - 1][cols - 1],
path: path.reverse(),
};
}
const board = [
[0, 1, 1, 1],
[1, 0, 0, 1],
[1, 1, 1, 1],
];
const result = maxCoins(board);
console.log("最大硬币数:", result.maxCoins);
console.log("路径:", result.path);