20240322 Finished

This commit is contained in:
jackfiled 2024-03-22 08:50:36 +08:00
parent 547630c8ce
commit fd3ad71cc0
2 changed files with 73 additions and 1 deletions

View File

@ -80,4 +80,5 @@ mod p310_minimum_height_trees;
mod p303_range_sum_query_immutable;
mod p1793_maximum_score_of_a_good_subarray;
mod p1969_minimum_non_zero_product_of_the_array_elements;
mod p2671_frequency_tracker;
mod p2671_frequency_tracker;
mod p2617_minimum_number_of_visited_cells_in_a_grid;

View File

@ -0,0 +1,71 @@
/**
* [2617] Minimum Number of Visited Cells in a Grid
*/
pub struct Solution {}
// submission codes start here
use std::{cmp::Reverse, collections::BinaryHeap};
impl Solution {
pub fn minimum_visited_cells(grid: Vec<Vec<i32>>) -> i32 {
let height = grid.len();
let width = grid[0].len();
let mut column_heaps: Vec<BinaryHeap<(Reverse<i32>, usize)>> = vec![BinaryHeap::new(); width];
let mut row_heap: BinaryHeap<(Reverse<i32>, usize)> = BinaryHeap::new();
let mut dis = 0;
for (i, row) in grid.iter().enumerate() {
row_heap.clear();
for (j, &node) in row.iter().enumerate() {
while !row_heap.is_empty() && row_heap.peek().unwrap().1 < j {
row_heap.pop();
}
let column_heap = &mut column_heaps[j];
while !column_heap.is_empty() && column_heap.peek().unwrap().1 < i {
column_heap.pop();
}
dis = if i > 0 || j > 0 {
i32::MAX
} else {
1
};
if let Some((d, _)) = row_heap.peek() {
dis = d.0 + 1;
}
if let Some((d, _)) = column_heap.peek() {
dis = dis.min(d.0 + 1);
}
if node > 0 && dis < i32::MAX {
let node = node as usize;
row_heap.push((Reverse(dis), node + j));
column_heap.push((Reverse(dis), node + i));
}
}
}
if dis < i32::MAX {
dis
} else {
-1
}
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2617() {
}
}