use std::io::*; fn main() { let mut s: String = String::new(); std::io::stdin().read_to_string(&mut s).ok(); let mut itr = s.trim().split_whitespace(); let w: usize = itr.next().unwrap().parse().unwrap(); let h: usize = itr.next().unwrap().parse().unwrap(); let grid: Vec> = (0..h) .map(|_| itr.next().unwrap().chars().collect()) .collect(); let mut cav = Vec::new(); let mut used = vec![false; h * w]; let mut end = false; let dx: Vec = [0, -1, 0, 1, -1, 1, -1, 1].to_vec(); let dy: Vec = [1, 0, -1, 0, -1, 1, 1, -1].to_vec(); for i in 0..h { for j in 0..w { if grid[i][j] == '.' { let mut q = std::collections::VecDeque::new(); q.push_back((i, j)); cav.push((i, j)); used[i * w + j] = true; while let Some((y, x)) = q.pop_front() { for i in 0..4 { let nx = x as isize + dx[i]; let ny = y as isize + dy[i]; if 0 <= nx && nx < w as isize && 0 <= ny && ny < h as isize && !used[ny as usize * w + nx as usize] && grid[ny as usize][nx as usize] == '.' { cav.push((ny as usize, nx as usize)); used[ny as usize * w + nx as usize] = true; q.push_back((ny as usize, nx as usize)); } } } end = true; break; } } if end { break; } } let mut ans = 1 << 30; for i in 0..h { for j in 0..w { if grid[i][j] == '.' && !used[i * w + j] { for k in 0..cav.len() { ans = std::cmp::min( ans, (i as isize - cav[k].0 as isize).abs() + (j as isize - cav[k].1 as isize).abs() - 1, ); } } } } println!("{}", ans); }