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
32
33
34
35
36
37
38
39
40
41
42
|
impl Solution {
pub fn longest_v_segment(grid: Vec<Vec<i32>>) -> i32 {
use std::collections::HashMap;
let n = grid.len();
let m = grid[0].len();
let dirs = [(1,1),(1,-1),(-1,1),(-1,-1)];
let mut memo = HashMap::new();
fn dp(r: i32, c: i32, d: usize, turned: i32, idx: i32, grid: &Vec<Vec<i32>>, memo: &mut HashMap<(i32,i32,usize,i32,i32),i32>) -> i32 {
let n = grid.len() as i32;
let m = grid[0].len() as i32;
if r < 0 || r >= n || c < 0 || c >= m { return 0; }
let expect = if idx == 0 { 1 } else if idx%2 == 1 { 2 } else { 0 };
if grid[r as usize][c as usize] != expect { return 0; }
let key = (r,c,d,turned,idx);
if let Some(&v) = memo.get(&key) { return v; }
let mut res = 1;
let (dr, dc) = dirs[d];
let ni = r+dr; let nj = c+dc;
let next_idx = if idx == 0 { 1 } else { 3-idx };
res = res.max(1+dp(ni, nj, d, turned, next_idx, grid, memo));
if turned == 0 {
let nd = (d+1)%4;
let (ndr, ndc) = dirs[nd];
let ni2 = r+ndr; let nj2 = c+ndc;
res = res.max(1+dp(ni2, nj2, nd, 1, next_idx, grid, memo));
}
memo.insert(key, res);
res
}
let mut ans = 0;
for i in 0..n as i32 {
for j in 0..m as i32 {
if grid[i as usize][j as usize] == 1 {
for d in 0..4 {
ans = ans.max(dp(i,j,d,0,0,&grid,&mut memo));
}
}
}
}
if ans >= 2 { ans } else { 0 }
}
}
|