3742. 网格中得分最大的路径
This commit is contained in:
parent
6213d83856
commit
fa937a142f
43
src/main.rs
43
src/main.rs
|
|
@ -4,37 +4,38 @@ mod arr;
|
|||
|
||||
struct Solution {}
|
||||
impl Solution {
|
||||
pub fn min_operations(grid: Vec<Vec<i32>>, x: i32) -> i32 {
|
||||
if grid.len() == 1 && grid[0].len() == 1 {
|
||||
return 0;
|
||||
pub fn max_path_score(grid: Vec<Vec<i32>>, k: i32) -> i32 {
|
||||
let k = (k as usize + 1).min(grid.len() + grid[0].len() + 1);
|
||||
let mut dp = vec![vec![vec![-1;k]; grid[0].len()]; grid.len()];
|
||||
for i in 0..k {
|
||||
dp[0][0][i] = 0;
|
||||
}
|
||||
let mut arr = vec![0; grid[0].len() * grid.len()];
|
||||
for i in 0..grid.len() {
|
||||
for j in 0..grid[i].len() {
|
||||
arr[i * grid[0].len() + j] = grid[i][j];
|
||||
}
|
||||
}
|
||||
arr.sort_unstable();
|
||||
let a = arr[arr.len() / 2];
|
||||
let check = |grid: &Vec<Vec<i32>>, a: i32| {
|
||||
let mut ans = 0;
|
||||
for i in 0..grid.len() {
|
||||
for j in 0..grid[i].len() {
|
||||
if grid[i][j].abs_diff(a) as i32 % x != 0 {
|
||||
return -1;
|
||||
for j in 0..grid[0].len() {
|
||||
let cost = if grid[i][j] > 0 { 1 } else { 0 };
|
||||
let score = grid[i][j];
|
||||
for p in cost..k {
|
||||
let mut ans = -1;
|
||||
if j > 0 && dp[i][j - 1][p - cost] != -1 {
|
||||
ans = dp[i][j - 1][p - cost];
|
||||
}
|
||||
ans += grid[i][j].abs_diff(a) as i32 / x;
|
||||
if i > 0 && dp[i - 1][j][p - cost] != -1 {
|
||||
ans = ans.max(dp[i - 1][j][p - cost]);
|
||||
}
|
||||
dp[i][j][p] = dp[i][j][p].max(if ans == -1 { -1 } else { ans + score });
|
||||
}
|
||||
}
|
||||
ans
|
||||
};
|
||||
check(&grid, a)
|
||||
}
|
||||
*dp[grid.len() - 1][grid[0].len() - 1]
|
||||
.iter()
|
||||
.max()
|
||||
.unwrap_or(&0)
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!(
|
||||
"{:?}",
|
||||
Solution::min_operations(make_matrix("[[1,1,100]]"), 1)
|
||||
Solution::max_path_score(make_matrix("[[0, 1],[2, 0]]"), 1)
|
||||
);
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue