use std::collections::BTreeMap; fn main() { let mut sc = Scanner::new(); let h = sc.usize(); let w = sc.usize(); let mut a = vec![vec![0; w]; h-2]; for i in 0..h-2 { a[i] = sc.vec::(w); } for i in 0..h-2 { for j in 0..w { if a[i][j] == -1 { a[i][j] = std::i64::MAX / 100; } }} let mut memo = BTreeMap::new(); let mut ans = std::i64::MAX; for i in 0..h-2 { ans = ans.min(f(i, 0, h, w, &a, &mut memo)); } if ans >= std::i64::MAX / 100 { ans = -1; } println!("{}", ans); } fn f(i:usize, j:usize, h:usize, w:usize, a:&Vec>, memo:&mut BTreeMap<(usize,usize), i64>) -> i64 { if j == w { return 0; } if let Some(&x) = memo.get(&(i, j)) { return x; } let mut res = std::i64::MAX; if i > 0 { res = res.min(f(i-1, j+1, h, w, a, memo) + a[i][j]); } res = res.min(f(i, j+1, h, w, a, memo) + a[i][j]); if i+1 < h-2 { res = res.min(f(i+1, j+1, h, w, a, memo) + a[i][j]); } memo.insert((i, j), res); res } struct Scanner { s : std::collections::VecDeque } #[allow(unused)] impl Scanner { fn new() -> Self { use std::io::Read; let mut s = String::new(); std::io::stdin().read_to_string(&mut s).unwrap(); Self { s : s.split_whitespace().map(|s| s.to_string()).collect() } } fn reload(&mut self) -> () { use std::io::Read; let mut s = String::new(); std::io::stdin().read_to_string(&mut s).unwrap(); self.s = s.split_whitespace().map(|s| s.to_string()).collect(); } fn usize(&mut self) -> usize { self.input() } fn usize1(&mut self) -> usize { self.input::() - 1 } fn isize(&mut self) -> isize { self.input() } fn i32(&mut self) -> i32 { self.input() } fn i64(&mut self) -> i64 { self.input() } fn i128(&mut self) -> i128 { self.input() } fn u8(&mut self) -> u8 { self.input() } fn u32(&mut self) -> u32 { self.input() } fn u64(&mut self) -> u64 { self.input() } fn u128(&mut self) -> u128 { self.input() } fn edge(&mut self) -> (usize, usize) { (self.usize1(), self.usize1()) } fn edges(&mut self, m : usize) -> Vec<(usize, usize)> { let mut e = Vec::with_capacity(m); for _ in 0..m { e.push(self.edge()); } e } fn wedge(&mut self) -> (usize, usize, T) { (self.usize1(), self.usize1(), self.input()) } fn wedges(&mut self, m : usize) -> Vec<(usize, usize, T)> { let mut e = Vec::with_capacity(m); for _ in 0..m { e.push(self.wedge()); } e } fn input(&mut self) -> T where T: std::str::FromStr { if self.s.is_empty() { self.reload(); } if let Some(head) = self.s.pop_front() { head.parse::().ok().unwrap() } else { panic!() } } fn tuple(&mut self) -> (T, U) where T: std::str::FromStr, U: std::str::FromStr { (self.input(), self.input()) } fn vec(&mut self, n: usize) -> Vec where T: std::str::FromStr { if self.s.is_empty() { self.reload(); } self.s.drain(..n).map(|s| s.parse::().ok().unwrap() ).collect::>() } fn nvec(&mut self) -> Vec where T: std::str::FromStr { let n : usize = self.input(); self.vec(n) } fn chars(&mut self) -> Vec { let s : String = self.input(); s.chars().collect() } fn bytes(&mut self) -> Vec { let s : String = self.input(); s.bytes().collect() } }