diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 4c2f5c4..ba5bd23 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -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; \ No newline at end of file +mod p2671_frequency_tracker; +mod p2617_minimum_number_of_visited_cells_in_a_grid; \ No newline at end of file diff --git a/src/problem/p2617_minimum_number_of_visited_cells_in_a_grid.rs b/src/problem/p2617_minimum_number_of_visited_cells_in_a_grid.rs new file mode 100644 index 0000000..5afeae8 --- /dev/null +++ b/src/problem/p2617_minimum_number_of_visited_cells_in_a_grid.rs @@ -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>) -> i32 { + let height = grid.len(); + let width = grid[0].len(); + + let mut column_heaps: Vec, usize)>> = vec![BinaryHeap::new(); width]; + let mut row_heap: BinaryHeap<(Reverse, 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() { + } +}