pub mod scanner { pub struct Scanner { buf: Vec, } impl Scanner { pub fn new() -> Self { Self { buf: vec![] } } pub fn new_from(source: &str) -> Self { let source = String::from(source); let buf = Self::split(source); Self { buf } } pub fn next(&mut self) -> T { loop { if let Some(x) = self.buf.pop() { return x.parse().ok().expect(""); } let mut source = String::new(); std::io::stdin().read_line(&mut source).expect(""); self.buf = Self::split(source); } } fn split(source: String) -> Vec { source .split_whitespace() .rev() .map(String::from) .collect::>() } } } use std::cmp::Reverse; use crate::scanner::Scanner; const DIJ: [(usize, usize); 8] = [ (!0, !0), (!0, 0), (!0, 1), (0, !0), (0, 1), (1, !0), (1, 0), (1, 1), ]; fn main() { let mut scanner = Scanner::new(); let t: usize = 1; for _ in 0..t { solve(&mut scanner); } } fn solve(scanner: &mut Scanner) { let h: usize = scanner.next(); let w: usize = scanner.next(); let h = h - 2; let mut grid = vec![vec![-1 as isize; w]; h]; let mut wall = vec![vec![false; w]; h]; for i in 0..h { for j in 0..w { grid[i][j] = scanner.next(); wall[i][j] = grid[i][j] == -1; } } let inf = 1e18 as isize; let mut dist = vec![vec![inf; w]; h]; let mut que = std::collections::BinaryHeap::new(); for i in 0..h { if !wall[i][0] { dist[i][0] = grid[i][0]; que.push(Reverse((grid[i][0], i, 0))); } } while let Some(Reverse((cd, ci, cj))) = que.pop() { if dist[ci][cj] < cd { continue; } for &(di, dj) in DIJ.iter() { let ni = ci + di; let nj = cj + dj; if h <= ni || w <= nj || wall[ni][nj] { continue; } let nd = cd + grid[ni][nj]; if dist[ni][nj] <= nd { continue; } dist[ni][nj] = nd; que.push(Reverse((nd, ni, nj))); } } let mut ans = inf; for i in 0..h { if dist[i][w - 1] < inf { ans = ans.min(dist[i][w - 1]); } } if ans == inf { ans = -1; } println!("{}", ans); }