3212. 统计 X 和 Y 频数相等的子矩阵数量

This commit is contained in:
2026-03-19 09:25:38 +08:00
parent bb640829ee
commit bb6a7dc773
2 changed files with 162 additions and 18 deletions
+39 -18
View File
@@ -1,29 +1,53 @@
struct Solution;
mod arr;
impl Solution {
pub fn count_submatrices(mut grid: Vec<Vec<i32>>, k: i32) -> i32 {
pub fn number_of_submatrices(mut grid: Vec<Vec<char>>) -> i32 {
let mut arr = vec![vec![(0, 0); grid[0].len()]; grid.len()];
match grid[0][0] {
'.' => arr[0][0] = (0, 0),
'X' => arr[0][0] = (0, 1),
'Y' => arr[0][0] = (1, 0),
_ => {}
}
let mut ans = 0;
if grid[0][0] <= k {
ans += 1;
}else {
return 0;
}
for i in 1..grid[0].len() {
grid[0][i] += grid[0][i-1];
if grid[0][i] <= k {
let (mut y, mut x) = arr[0][i - 1];
match grid[0][i] {
'X' => x += 1,
'Y' => y += 1,
_ => {}
}
if x == y && x != 0 {
ans += 1;
}
arr[0][i] = (y, x)
}
for i in 1.. grid.len() {
grid[i][0] += grid[i-1][0];
if grid[i][0] <= k {
for i in 1..grid.len() {
let (mut y, mut x) = arr[i - 1][0];
match grid[i][0] {
'X' => x += 1,
'Y' => y += 1,
_ => {}
}
arr[i][0] = (y, x);
if x == y && x != 0 {
ans += 1;
}
for j in 1.. grid[i].len() {
grid[i][j] += grid[i-1][j] + grid[i][j-1] - grid[i-1][j-1];
if grid[i][j] <= k {
for j in 1..grid[i].len() {
let (ya, xa) = arr[i - 1][j];
let (yb, xb) = arr[i][j - 1];
let (yc, xc) = arr[i - 1][j - 1];
let (mut x, mut y) = (xa + xb - xc, ya + yb - yc);
match grid[i][j] {
'X' => x += 1,
'Y' => y += 1,
_ => {}
}
if x == y && x != 0 {
ans += 1;
}
arr[i][j] = (y, x);
}
}
ans
@@ -31,9 +55,6 @@ impl Solution {
}
fn main() {
let result = Solution::count_submatrices(arr::make_matrix(
"[[7,2,9],[1,5,0],[2,6,6]]"
), 20);
let result = Solution::number_of_submatrices(arr::make_char_matrix(r#"[["X","Y"],["X","Y"]]"#));
println!("{:?}", result);
}