use std::collections::*; type Deque = VecDeque; fn main() { input! { h: usize, w: usize, s: [bytes; h], } let mut diff = vec![0usize]; for i in 1..=3 { diff.push(i); diff.push(!i + 1); } let mut s = s; for s in s.iter_mut() { s.insert(0, b'#'); s.push(b'#'); } s.insert(0, vec![b'#'; w + 2]); s.push(vec![b'#'; w + 2]); let inf = std::u32::MAX / 10; let mut dp = vec![vec![inf; w + 2]; h + 2]; let mut deq = Deque::new(); for i in 4..=h { dp[i][0] = 0; deq.push_back((i, 0)); } for j in 1..=(w - 4) { dp[h + 1][j] = 0; deq.push_back((h + 1, j)); } while let Some((x, y)) = deq.pop_front() { let d = dp[x][y]; for dx in diff.iter() { for dy in diff.iter() { let x = x + *dx; let y = y + *dy; if !(x < h + 2 && y < w + 2) { continue; } if (x < 4 && y < 4) || (x >= h - 2 && y >= w - 2) { continue; } if s[x][y] == b'#' { if dp[x][y].chmin(d) { deq.push_front((x, y)); } } else { if dp[x][y].chmin(d + 1) { deq.push_back((x, y)); } } } } } let mut ans = inf; for i in 1..=(h - 3) { ans.chmin(dp[i][w + 1]); } for j in 4..=w { ans.chmin(dp[0][j]); } println!("{}", ans); } // ---------- begin input macro ---------- // reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 #[macro_export] macro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); input_inner!{iter, $($r)*} }; ($($r:tt)*) => { let s = { use std::io::Read; let mut s = String::new(); std::io::stdin().read_to_string(&mut s).unwrap(); s }; let mut iter = s.split_whitespace(); input_inner!{iter, $($r)*} }; } #[macro_export] macro_rules! input_inner { ($iter:expr) => {}; ($iter:expr, ) => {}; ($iter:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($iter, $t); input_inner!{$iter $($r)*} }; } #[macro_export] macro_rules! read_value { ($iter:expr, ( $($t:tt),* )) => { ( $(read_value!($iter, $t)),* ) }; ($iter:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($iter, $t)).collect::>() }; ($iter:expr, chars) => { read_value!($iter, String).chars().collect::>() }; ($iter:expr, bytes) => { read_value!($iter, String).bytes().collect::>() }; ($iter:expr, usize1) => { read_value!($iter, usize) - 1 }; ($iter:expr, $t:ty) => { $iter.next().unwrap().parse::<$t>().expect("Parse error") }; } // ---------- end input macro ---------- // ---------- begin chmin, chmax ---------- pub trait ChangeMinMax { fn chmin(&mut self, x: Self) -> bool; fn chmax(&mut self, x: Self) -> bool; } impl ChangeMinMax for T { fn chmin(&mut self, x: Self) -> bool { *self > x && { *self = x; true } } fn chmax(&mut self, x: Self) -> bool { *self < x && { *self = x; true } } } // ---------- end chmin, chmax ----------