You are given a square board of characters. You can move on the board starting at the bottom right square marked with the character ‘S’.
You need to reach the top left square marked with the character ‘E’. The rest of the squares are labeled either with a numeric character 1, 2, …, 9 or with an obstacle ‘X’. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there.
Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 + 7.
In case there is no path, return [0, 0].
Example 1:
Input: board = [“E23”,“2X2”,“12S”]
Output: [7,1]
Example 2:
Input: board = [“E12”,“1X1”,“21S”]
Output: [4,2]
Example 3:
Input: board = [“E11”,“XXX”,“11S”]
Output: [0,0]
Constraints:
- 2 <= board.length == board[i].length <= 100
用 dp 来解, dp[i][j][0]代表从 board[i][j]到终点的最大得分, dp[i][j][1]代表从 board[i][j]到终点的路径数量, 对于任意一点(i, j), 最大分数 max_score = max(dp[i-1][j][0], dp[i][j-1][0], dp[i-1, j-1][0]) + board[i][j], 最大分数的路径数量是 3 条路径中分数与 max_score 相等的路径数量的加和
impl Solution {
const M: i64 = 10i64.pow(9) + 7;
fn dp(board: &Vec<Vec<i32>>, i: usize, j: usize, cache: &mut Vec<Vec<Vec<i32>>>) -> Vec<i32> {
if i == 0 && j == 0 {
return vec![0, 1];
}
if board[i][j] == -1 {
return vec![0, 0];
}
let up = if i > 0 {
if cache[i - 1][j][0] >= 0 {
cache[i - 1][j].clone()
} else {
Solution::dp(board, i - 1, j, cache)
}
} else {
vec![0, 0]
};
let left = if j > 0 {
if cache[i][j - 1][0] >= 0 {
cache[i][j - 1].clone()
} else {
Solution::dp(board, i, j - 1, cache)
}
} else {
vec![0, 0]
};
let up_left = if i > 0 && j > 0 {
if cache[i - 1][j - 1][0] >= 0 {
cache[i - 1][j - 1].clone()
} else {
Solution::dp(board, i - 1, j - 1, cache)
}
} else {
vec![0, 0]
};
let max_score = up[0].max(left[0]).max(up_left[0]);
let mut paths = 0i64;
if up[0] == max_score {
paths += up[1] as i64;
}
if left[0] == max_score {
paths += left[1] as i64;
}
if up_left[0] == max_score {
paths += up_left[1] as i64;
}
if paths == 0 {
cache[i][j] = vec![0, 0];
return vec![0, 0];
}
cache[i][j] = vec![max_score + board[i][j], (paths % Solution::M) as i32];
vec![max_score + board[i][j], (paths % Solution::M) as i32]
}
pub fn paths_with_max_score(board: Vec<String>) -> Vec<i32> {
let board = board.into_iter().fold(Vec::new(), |mut l, s| {
let values = s
.chars()
.map(|c| match c {
'S' | 'E' => 0,
'X' => -1,
_ => c.to_string().parse::<i32>().unwrap(),
})
.collect::<Vec<i32>>();
l.push(values);
l
});
Solution::dp(
&board,
board.len() - 1,
board[0].len() - 1,
&mut vec![vec![vec![-1, -1]; board[0].len()]; board.len()],
)
}
}