use std::collections::HashSet; fn main() { let mut hw = String::new(); std::io::stdin().read_line(&mut hw).ok(); let hw: Vec = hw.trim().split_whitespace().map(|s| s.parse().unwrap()).collect(); let h = hw[0]; let w = hw[1]; let grid = (0..h).map(|_| { let mut temp = String::new(); std::io::stdin().read_line(&mut temp).ok(); let temp = temp.trim(); temp.chars().collect::>() }) .collect::>>(); let mut result = vec![]; let mut fronts = HashSet::new(); result.push(grid[0][0]); fronts.insert((0, 0)); for _ in 0..h+w-2 { let mut nexts = HashSet::new(); let mut candc = None; for &(x, y) in fronts.iter() { if x + 1 < h { if candc.is_none() { candc = Some(grid[x+1][y]); nexts.insert((x+1, y)); } else if candc.unwrap() as usize > grid[x+1][y] as usize { candc = Some(grid[x+1][y]); nexts = HashSet::new(); nexts.insert((x+1, y)); } else if candc.unwrap() as usize == grid[x+1][y] as usize { nexts.insert((x+1, y)); } } if y + 1 < w { if candc.is_none() { candc = Some(grid[x][y+1]); nexts.insert((x, y+1)); } else if candc.unwrap() as usize > grid[x][y+1] as usize { candc = Some(grid[x][y+1]); nexts = HashSet::new(); nexts.insert((x, y+1)); } else if candc.unwrap() as usize == grid[x][y+1] as usize { nexts.insert((x, y+1)); } } } result.push(candc.unwrap()); fronts = nexts; } for c in result.into_iter() { print!("{}", c); } println!(); }