From 7418f4f62c26988cf5367e00bf117a8a0d1c3f88 Mon Sep 17 00:00:00 2001 From: SquidSpirit Date: Thu, 21 Aug 2025 22:35:47 +0800 Subject: [PATCH] feat: 1504_count_submatrices_with_all_ones --- .../Cargo.lock | 7 +++ .../Cargo.toml | 6 +++ .../src/lib.rs | 48 +++++++++++++++++++ 3 files changed, 61 insertions(+) create mode 100644 1504_count_submatrices_with_all_ones/Cargo.lock create mode 100644 1504_count_submatrices_with_all_ones/Cargo.toml create mode 100644 1504_count_submatrices_with_all_ones/src/lib.rs diff --git a/1504_count_submatrices_with_all_ones/Cargo.lock b/1504_count_submatrices_with_all_ones/Cargo.lock new file mode 100644 index 0000000..1a741ad --- /dev/null +++ b/1504_count_submatrices_with_all_ones/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "count_submatrices_with_all_ones" +version = "0.1.0" diff --git a/1504_count_submatrices_with_all_ones/Cargo.toml b/1504_count_submatrices_with_all_ones/Cargo.toml new file mode 100644 index 0000000..ec3310f --- /dev/null +++ b/1504_count_submatrices_with_all_ones/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "count_submatrices_with_all_ones" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/1504_count_submatrices_with_all_ones/src/lib.rs b/1504_count_submatrices_with_all_ones/src/lib.rs new file mode 100644 index 0000000..bbe1b5c --- /dev/null +++ b/1504_count_submatrices_with_all_ones/src/lib.rs @@ -0,0 +1,48 @@ +pub struct Solution; + +impl Solution { + pub fn num_submat(matrix: Vec>) -> i32 { + let m = matrix.len(); + let n = matrix[0].len(); + + let mut result = 0; + let mut heights = vec![0; n]; + for i in 0..m { + for j in 0..n { + if matrix[i][j] == 1 { + heights[j] += matrix[i][j]; + } else { + heights[j] = 0; + } + } + + let mut index_stack: Vec = vec![]; + let mut previos_less_index = vec![-1 as isize; n]; + for j in 0..n { + while let Some(&index) = index_stack.last() { + if heights[j] > heights[index] { + previos_less_index[j] = index as isize; + break; + } else { + index_stack.pop(); + } + } + index_stack.push(j); + } + + let mut sum = vec![0; n]; + for j in 0..n { + if previos_less_index[j] == -1 { + sum[j] = heights[j] * (j as i32 + 1); + } else { + sum[j] = sum[previos_less_index[j] as usize] + + heights[j] * (j as i32 - previos_less_index[j] as i32); + } + + result += sum[j]; + } + } + + result + } +}