1878. 矩阵中最大的三个菱形和

This commit is contained in:
li_chx 2026-03-16 09:27:43 +08:00
parent d5eafc86f4
commit 143ff15f87
Signed by: li_chx
GPG Key ID: 70D4985BB8180E92
1 changed files with 44 additions and 47 deletions

View File

@ -1,61 +1,58 @@
struct Solution; struct Solution;
mod arr; mod arr;
impl Solution { impl Solution {
pub fn construct(s: &mut Vec<char>, n: usize) { fn get_count(grid: &Vec<Vec<i32>>, x: usize, y: usize, i: usize) -> i32 {
for _ in s.len()..n { if i == 0 {
if s[s.len() - 1] == 'a' { return grid[y][x];
s.push('b');
} else {
s.push('a');
} }
let mut cnt = 0;
for t in 0..i {
cnt += grid[y + t][x + t];
cnt += grid[y + i + t][x + i - t];
cnt += grid[y + 2 * i - t][x - t];
cnt += grid[y + i - t][x - i + t];
} }
cnt
} }
pub fn get_happy_string(n: i32, k: i32) -> String { pub fn get_biggest_three(grid: Vec<Vec<i32>>) -> Vec<i32> {
let n = n as usize; let (mut m1, mut m2, mut m3) = (0, 0, 0);
let mut x = vec!['a'];
Self::construct(&mut x,n); for i in 0..grid.len() {
for _ in 1..k { let path = i * 2 + 1;
let mut have_ans = false; if path > grid.len() || path > grid[0].len() {
for j in (0..n).rev() {
if x[j] == 'a' {
have_ans = true;
if j == 0{
x = vec!['b'];
Self::construct(&mut x,n);
break; break;
} }
if x[j-1] == 'b'{ for j in i..grid[0].len() - i {
x[j] = 'c'; for k in 0..grid.len() - 2 * i {
}else { let cnt = Solution::get_count(&grid, j, k, i);
x[j] = 'b'; if cnt == m1 || cnt == m2 || cnt == m3 {
continue;
} }
x = x[0..j+1].to_vec(); if cnt > m1 {
Self::construct(&mut x,n); (m1, m2, m3) = (cnt, m1, m2);
break; } else if cnt > m2 {
} (m2, m3) = (cnt, m2);
if x[j] == 'b' { } else if cnt > m3 {
if j == 0 || x[j-1] != 'c' { m3 = cnt;
x[j] = 'c';
x = x[0..j+1].to_vec();
Self::construct(&mut x,n);
have_ans = true;
break;
} }
} }
} }
if !have_ans { }
return String::new(); let mut ret = vec![m1];
if m2 != 0 {
ret.push(m2);
if m3 != 0 {
ret.push(m3);
} }
} }
x.into_iter().collect() ret
} }
} }
fn main() { fn main() {
let result = Solution::get_happy_string( let result = Solution::get_biggest_three(arr::make_matrix(
10, "[[6,7,7,7,7]]",
100, ));
);
println!("{:?}", result); println!("{:?}", result);
} }