const DXY: [(usize, usize); 4] = [(!0, 0), (0, 1), (1, 0), (0, !0)]; use std::collections::VecDeque; use proconio::{input, marker::Usize1}; fn main() { input! { h: usize, w: usize, a: Usize1, b: Usize1, rc: [(Usize1, Usize1); 2], p: Usize1, q: Usize1, } let f = |i: usize, j: usize| rc[0].0 <= i && i <= rc[1].0 && rc[0].1 <= j && j <= rc[1].1; let mut dist: Vec>> = vec![vec![vec![1 << 60; 3]; w]; h]; let mut que = VecDeque::new(); que.push_back((a, b, 0, 0)); dist[a][b][0] = 0; while let Some((i, j, mut x, d)) = que.pop_front() { if f(i, j) { x = x.max(1); } if x == 1 && (i, j) == (p, q) { x = x.max(2); } if dist[i][j][x] == 1 << 60 { dist[i][j][x] = d; } for (dx, dy) in DXY { let (px, py) = (i + dx, j + dy); if px < h && py < w { let mut x = x; if f(px, py) { x = x.max(1); } if x == 1 && (px, py) == (p, q) { x = x.max(2); } if dist[px][py][x] == 1 << 60 { dist[px][py][x] = d + 1; que.push_back((px, py, x, d + 1)); } } } } println!("{}", dist[a][b][2]); }