3147. 从魔法师身上吸取的最大能量

This commit is contained in:
li-chx 2025-10-10 08:37:58 +08:00
parent aa1f5ac8c1
commit 60f0b5cd02
1 changed files with 11 additions and 39 deletions

View File

@ -2,39 +2,17 @@ mod arr;
struct Solution {}
impl Solution {
pub fn dfs(heights: &Vec<Vec<i32>>,arr: &mut Vec<Vec<bool>>,i:usize,j:usize ) {
let dirs = vec![(0,1),(0,-1),(1,0),(-1,0)];
for dir in dirs {
let (x,y) = (i as i32 + dir.0, j as i32 + dir.1);
if x>=0 && x<heights.len() as i32 && y>=0 && y<heights[0].len() as i32 && !arr[x as usize][y as usize] && heights[x as usize][y as usize]>=heights[i][j] {
arr[x as usize][y as usize] = true;
Self::dfs(heights,arr,x as usize,y as usize);
}
}
}
pub fn pacific_atlantic(heights: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let (m,n) = (heights.len(),heights[0].len());
let mut pacific = vec![vec![false;n];m];
let mut atlantic = vec![vec![false;n];m];
let mut ans = vec![];
for i in 0..m {
pacific[i][0] = true;
atlantic[i][n-1] = true;
Self::dfs(&heights,&mut pacific,i,0);
Self::dfs(&heights,&mut atlantic,i,n-1);
}
for j in 0..n {
pacific[0][j] = true;
atlantic[m-1][j] = true;
Self::dfs(&heights,&mut pacific,0,j);
Self::dfs(&heights,&mut atlantic,m-1,j);
}
for i in 0..m {
for j in 0..n {
if pacific[i][j] && atlantic[i][j] {
ans.push(vec![i as i32,j as i32]);
pub fn maximum_energy(mut energy: Vec<i32>, k: i32) -> i32 {
let mut ans = -1e9 as i32;
for i in 1..energy.len() {
if i as i32 - k >= 0 {
if energy[i - k as usize] > 0 {
energy[i] += energy[i - k as usize];
}
}
if i as i32 + k >= energy.len() as i32 {
ans = ans.max(energy[i]);
}
}
ans
}
@ -43,12 +21,6 @@ impl Solution {
fn main() {
// [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
// initial as a 2D vector
let arr = vec![
vec![1, 2, 2, 3, 5],
vec![3, 2, 3, 4, 4],
vec![2, 4, 5, 3, 1],
vec![6, 7, 1, 4, 5],
vec![5, 1, 1, 2, 4],
];
println!("{:?}", Solution::pacific_atlantic(arr));
let skills = vec![5, 2, -10, -5, 1];
println!("{:?}", Solution::maximum_energy(skills, 3));
}