#![allow(unused)] // use itertools::Itertools; use proconio::*; use std::{cmp::Reverse, collections::*, sync::{mpsc::RecvTimeoutError, BarrierWaitResult}}; const DIJ4: [(usize, usize); 4] = [(0, !0), (!0, 0), (0, 1), (1, 0)]; fn main() { input! { h: usize, w: usize, a: [[usize; w]; h] } let mut one_heap = BinaryHeap::new(); let mut zero_heap = BinaryHeap::new(); let mut one_seen = HashSet::new(); let mut zero_seen = HashSet::new(); let nv = nvs(0, 0, h, w); for (ni, nj) in nv { one_heap.push(Reverse((a[ni][nj], ni, nj))); } let nv = nvs(h-1, w-1, h, w); for (ni, nj) in nv { zero_heap.push(Reverse((a[ni][nj], ni, nj))); } one_seen.insert((0, 0)); zero_seen.insert((h-1, w-1)); for t in 0..h*w { let mut ok = true; if t%2 == 0 { let Reverse((_, i, j)) = one_heap.pop().unwrap(); one_seen.insert((i, j)); let nvs = nvs(i, j, h, w); for (ni, nj) in &nvs { if zero_seen.contains(&(*ni, *nj)) { ok = false; break; } } for (ni, nj) in nvs { if one_seen.contains(&(ni, nj)) { continue; } one_heap.push(Reverse((a[ni][nj], ni, nj))); } } else { let Reverse((_, i, j)) = zero_heap.pop().unwrap(); zero_seen.insert((i, j)); let nvs = nvs(i, j, h, w); for (ni, nj) in &nvs { if one_seen.contains(&(*ni, *nj)) { ok = false; break; } } for (ni, nj) in nvs { if zero_seen.contains(&(ni, nj)) { continue; } zero_heap.push(Reverse((a[ni][nj], ni, nj))) } } if !ok { println!("{}", t+1); return; } } } fn nvs(i: usize, j: usize, h: usize, w: usize) -> Vec<(usize, usize)> { let mut ret = vec![]; for (di, dj) in DIJ4 { let ni = i.wrapping_add(di); let nj = j.wrapping_add(dj); if !(ni < h && nj < w) { continue; } ret.push((ni, nj)) } ret }