#![allow(dead_code, unused_imports, unused_macros, non_snake_case)] fn main() { let [H, W] = read_words::()[..] else { return }; let A = (0 .. H).map(|_| read_words::() ).collect::>(); let mut colors = vec![vec![None; W]; H]; colors[0][0] = Some(true); colors[H - 1][W - 1] = Some(false); let mut pq = vec![BinaryHeap::new(); 2]; for &(i, j, c) in &[(0, 0, 1), (H - 1, W - 1, 0)] { neighbor4(i, j, H, W, |i2, j2| { if colors[i2][j2].is_none() { pq[c].push((Reverse(A[i2][j2]), i2, j2)); } }); } let mut ans = 0; 'main_loop: for t in 1 ..= H * W - 2 { let c = t % 2; while let Some((_, i, j)) = pq[c].pop() { if colors[i][j].is_some() { continue; } let mut fin = false; ans += 1; colors[i][j] = Some(c == 1); neighbor4(i, j, H, W, |i2, j2| { if colors[i2][j2].is_none() { pq[c].push((Reverse(A[i2][j2]), i2, j2)); } else if colors[i2][j2] != colors[i][j] { fin = true; } }); if fin { break 'main_loop; } break; } } println!("{}", ans); } type Int = i64; const MOD: Int = 1_000_000_007; const INF: Int = 1_000_000_000; const YESNO: [&'static str; 2] = ["Yes", "No"]; use std::collections::*; use std::cmp::Reverse; fn read_line() -> String { let mut buf = String::new(); std::io::stdin().read_line(&mut buf).ok(); buf } fn read_words() -> Vec where T::Err: std::fmt::Debug { read_line().split_whitespace().map(|x| T::from_str(x).unwrap() ).collect() } fn yes() { println!("{}", YESNO[0]); } fn no() { println!("{}", YESNO[1]); } fn yesno(c: bool) { println!("{}", if c { YESNO[0] } else { YESNO[1] }); } fn neighbor4(i: usize, j: usize, h: usize, w: usize, mut f: F) { if i > 0 { (f)(i - 1, j); } if i < h - 1 { (f)(i + 1, j); } if j > 0 { (f)(i, j - 1); } if j < w - 1 { (f)(i, j + 1); } }