1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
impl Solution {
pub fn get_max_grid_happiness(m: i32, n: i32, introverts_count: i32, extroverts_count: i32) -> i32 {
use std::collections::HashMap;
fn dfs(r: i32, c: i32, intro: i32, extro: i32, mask: i32, m: i32, n: i32, memo: &mut HashMap<(i32,i32,i32,i32,i32),i32>) -> i32 {
if r == m { return 0; }
if c == n { return dfs(r+1, 0, intro, extro, mask, m, n, memo); }
if let Some(&v) = memo.get(&(r,c,intro,extro,mask)) { return v; }
let mut res = dfs(r, c+1, intro, extro, (mask<<2)&((1<<(2*n))-1), m, n, memo);
if intro > 0 {
let mut happy = 120;
if c > 0 && ((mask>>(2*(n-1)))&3) == 1 { happy -= 30; }
if r > 0 && ((mask>>(2*(n-c-1)))&3) == 1 { happy -= 30; }
if c > 0 && ((mask>>(2*(n-1)))&3) == 2 { happy -= 30; }
if r > 0 && ((mask>>(2*(n-c-1)))&3) == 2 { happy -= 30; }
res = res.max(happy + dfs(r, c+1, intro-1, extro, ((mask<<2)|1)&((1<<(2*n))-1), m, n, memo));
}
if extro > 0 {
let mut happy = 40;
if c > 0 && ((mask>>(2*(n-1)))&3) == 1 { happy += 20; }
if r > 0 && ((mask>>(2*(n-c-1)))&3) == 1 { happy += 20; }
if c > 0 && ((mask>>(2*(n-1)))&3) == 2 { happy += 20; }
if r > 0 && ((mask>>(2*(n-c-1)))&3) == 2 { happy += 20; }
res = res.max(happy + dfs(r, c+1, intro, extro-1, ((mask<<2)|2)&((1<<(2*n))-1), m, n, memo));
}
memo.insert((r,c,intro,extro,mask), res);
res
}
let mut memo = HashMap::new();
dfs(0, 0, introverts_count, extroverts_count, 0, m, n, &mut memo)
}
}
|